//
//  PaymentsHistoryViewController.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 19.05.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

class PaymentsHistoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var rightButton: UIButton!
    @IBOutlet weak var pdfButton : UIButton!
    private let reuseCellIdentifier = "cell"
    var cashAndPaymentsViewController: CashAndPaymentsViewController?
    var payments: [[AnyObject]] = []
    var currentPaymentIndex: Int? {
        didSet {
            if let currentPaymentIndex = currentPaymentIndex {
                let firstPayment = (payments[currentPaymentIndex][1] as! [Payment]).first!
                dateLabel.text = firstPayment.dateAndMonthFormat()
                changeButton(currentCursorPosition())
                tableView.reloadData()
            }
        }
    }
    
    @IBOutlet weak var dateLabel: UILabel!
    
    @IBAction func leftButton_touchUpInside(sender: UIButton) {
        changePeriod(false)
    }
    
    @IBAction func rightButton_touchUpInside(sender: UIButton) {
        changePeriod(true)
    }
    
    @IBAction func pdfButton_click(sender: UIButton) {
        var urlString = "http://telecom.kz/api/get_year_history?token=\(Facade.accessToken!)&client_id=\(Facade.clientId!)"
        let vc = KTWebViewController(url: urlString)
        vc.title = LS("publishedCashes_pdfViewer_title")
        vc.showCloseButton()
        showViewController(vc, sender: self)
    }
    
    
    private func currentCursorPosition() -> ItemPosition {
        return payments.count == 1 ? .FirstLast : currentPaymentIndex == payments.count - 1 ? .Last : currentPaymentIndex == 0 ? .First : .None
    }
    
    private func changeButton(itemPosition: ItemPosition) {
        rightButton.hidden = itemPosition == .FirstLast ? true : itemPosition == .Last
        leftButton.hidden = itemPosition == .FirstLast ? true : itemPosition == .First
    }
    
    private func changePeriod(isNext: Bool) {
        if let currentPaymentIndex = currentPaymentIndex {
            if isNext {
                self.currentPaymentIndex = currentPaymentIndex < payments.count - 1 ? currentPaymentIndex + 1 : currentPaymentIndex
            } else {
                self.currentPaymentIndex = currentPaymentIndex > 0 ? currentPaymentIndex - 1 : currentPaymentIndex
            }
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localize()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureViews()
        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 configureViews() {
        dateLabel.textColor = Color.DarkColorForText
        configureTableView()
    }
    
    private func configureTableView() {
        tableView.estimatedRowHeight = 150
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
    private func getNumberOfRows() -> Int {
        return payments.count > 0 ? (payments[currentPaymentIndex!][1] as! [Payment]).count : 0
    }
    
    private func createPdfButtonCell(tableView : UITableView, indexPath: NSIndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCellWithIdentifier("pdfCell", forIndexPath: indexPath)
    }
    
    
    
}

// UITableViewDataSource
extension PaymentsHistoryViewController {
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell : UITableViewCell
        if indexPath.row < getNumberOfRows() {
            cell = tableView.dequeueReusableCellWithIdentifier(reuseCellIdentifier, forIndexPath: indexPath) as! PaymentHistoryCell
            (cell as! PaymentHistoryCell).fillCell((payments[currentPaymentIndex!][1] as! [Payment])[indexPath.row])
        } else {
            cell = createPdfButtonCell(tableView, indexPath: indexPath)
            cell.hideSeparatorLine()
        }
        
        //cell.selectionStyle = .None
        return cell
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var i = getNumberOfRows()
        
        if (i != 0) {
            i = i+1
            tableView.separatorStyle = .SingleLine
            tableView.backgroundView = nil
        }
        else {
            let noDataLabel: UILabel     = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
            noDataLabel.text          = LS("no_data")
            noDataLabel.textColor     = UIColor.blackColor()
            noDataLabel.textAlignment = NSTextAlignment.Center
            tableView.backgroundView  = noDataLabel
            tableView.separatorStyle  = UITableViewCellSeparatorStyle.None
        }
        
        return i///i == 0 ? 0 : i + 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        var numOfSections: Int = 0
        if getNumberOfRows() != 0
        {
            tableView.separatorStyle = .SingleLine
            numOfSections            = 1
            tableView.backgroundView = nil
        }
        else
        {
            let noDataLabel: UILabel     = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
            noDataLabel.text          = LS("no_data")
            noDataLabel.textColor     = UIColor.blackColor()
            noDataLabel.textAlignment = NSTextAlignment.Center
            tableView.backgroundView  = noDataLabel
            tableView.separatorStyle  = UITableViewCellSeparatorStyle.None
        }
        return numOfSections
    }
}

extension PaymentsHistoryViewController {
    override var localizedId: String {
        return "payments_history"
    }
}
