//
//  FeedPaymentCell.swift
//  kt
//
//  Created by neox on 16.08.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import UIKit

class FeedPaymentCell: UITableViewCell {
    
    @IBOutlet weak var lastPay: UILabel!
    @IBOutlet weak var balance: UILabel!
    @IBOutlet weak var payButton: BlueButton!
    @IBOutlet weak var refreshButton: UIImageView!
    
    var navController : UINavigationController?
    
    var payments: [[AnyObject]] = []
    var currentPaymentIndex: Int? {
        didSet {
            if let currentPaymentIndex = currentPaymentIndex {
                let firstPayment = (payments[currentPaymentIndex][1] as! [Payment]).first!
                lastPay.text = LocalizedString("payment_last_format", description: "Последний платеж: ") + firstPayment.yyyyMMdd()!
            }
        }
    }
    
    override func awakeFromNib() {
        
        super.awakeFromNib()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FeedPaymentCell.updateLabels), name: AbonentInfoManager.NotificationNames.Update, object: AbonentInfoManager.sharedInstance)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FeedPaymentCell.showError(_:)), name: AbonentInfoManager.NotificationNames.Error, object: AbonentInfoManager.sharedInstance)
   
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(FeedPaymentCell.imageTapped(_:)))
        refreshButton.userInteractionEnabled = true
        refreshButton.addGestureRecognizer(tapGestureRecognizer)
    
    }
    
    func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) {
        SpinneredAlert.show(self.navController!)
        AbonentInfoManager.sharedInstance.updateUserInfo()
        requestLastPayment()
    }

    func requestLastPayment() {
        Facade.sharedInstance().getPaymentList({ (payments) in
            self.payments = payments
            self.currentPaymentIndex = payments.count > 0 ? payments.count - 1 : nil
            }, onError: { (error) in
                AlertViewUtil.showIncorrectAlert(error)
            }, onFinish: { () in
        })
    }
    
    func updateLabels() {
        if let abonentInfo = AbonentInfoManager.sharedInstance.abonentInfo {
            let currency = "\(abonentInfo.balance ?? 0)".stringByReplacingOccurrencesOfString(".", withString: ",")
            balance.text = "\(currency) тг."
        }
        requestLastPayment()
    }
    
    func showError(notification: NSNotification) {
        
    }
    
    @IBAction func payButtonPressed(sender: AnyObject) {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let destination = storyboard.instantiateViewControllerWithIdentifier("OnlinePaymentViewController") as! OnlinePaymentViewController
        navController!.pushViewController(destination, animated: true)
    }
}
