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

import Foundation
import UIKit

enum ItemPosition {
    case First
    case Last
    case FirstLast
    case None
}

class PublishedCashesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var noDataLabel: UILabel!
    @IBOutlet weak var rightButton: UIButton!
    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var pdfButton : UIButton!
    @IBOutlet weak var indicator: UIActivityIndicatorView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var periodLabel: UILabel!
    let cellIdentifier = "cell"
    let payCellIdentifier = "payCell"
    var cashAndPaymentsViewController: CashAndPaymentsViewController?
    var periodId = 0
    
    @IBAction func btnDetails_click(sender: AnyObject) {
        
        self.performSegueWithIdentifier("bill_positions", sender: nil)
        
//        let vc = self.storyboard!.instantiateViewControllerWithIdentifier("BillPositionsModalViewController") as! BillPositionsModalViewController
//        vc.billPositions = currentBill!.billPositions
//        self.navigationController?.presentViewController(vc, animated: true, completion: nil)
        
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        switch segue.identifier! {
        case "bill_positions":
            let nav = segue.destinationViewController as! UINavigationController
            let vc = nav.topViewController as! BillPositionsModalViewController
            vc.billPositions = self.currentBill!.billPositions
            break
        default:
            break
        }
    }
    
    var currentBill: Bill? {
        didSet {
            self.noDataLabel.setTextAndSizeToFit(LS("no_data"))
            self.noDataLabel.hidden = self.currentBill != nil
            tableView.hidden = self.currentBill == nil
            tableView.reloadData()
        }
    }
    var periods: [ReportPeriod] = []
    var periodIdsBills: [String: Bill] = [String: Bill]()
    var currentPeriodIndex: Int? {
        didSet {
            changeButton(currentCursorPosition())
            if let currentPeriodIndex = currentPeriodIndex {
                periodLabel.text = self.periods[currentPeriodIndex].name
                self.fetchNewData()
            }
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localizeViews()
    }
    
    func localizeViews() {
        localize()
        self.noDataLabel.setTextAndSizeToFit(LS("no_data"))
    }
    
    private func configureTableView() {
        tableView.estimatedRowHeight = 250
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
    func configureViews() {
        self.view.bringSubviewToFront(noDataLabel)
        configureTableView()
        periodLabel.textColor = Color.DarkColorForText
        noDataLabel.textColor = Color.DarkColorForText
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureViews()
        //pdfButton.titleLabel?.text = LS("pdfButton")
        Facade.sharedInstance().getReportsPeriodList( { (periods) in
            self.periods = periods
            self.currentPeriodIndex = periods.count > 0 ? periods.count - 1 : nil
            }, onError: { (error) in
                AlertViewUtil.showErrorAlert(message: error)
        })
    }
    
    private func changePeriod(isNext: Bool) {
        if let currentPeriodIndex = currentPeriodIndex {
            if isNext {
                self.currentPeriodIndex = currentPeriodIndex < periods.count - 1 ? currentPeriodIndex + 1 : currentPeriodIndex
            } else {
                self.currentPeriodIndex = currentPeriodIndex > 0 ? currentPeriodIndex - 1 : currentPeriodIndex
            }
        }
    }
    
    @IBAction func left_touchUpInside(sender: UIButton) {
        changePeriod(false)
    }
    
    @IBAction func right_touchUpInside(sender: UIButton) {
        changePeriod(true)
    }
    
    @IBAction func pdfButton_click(sender: UIButton) {
        let accountId = String(Facade.accountId!)
        let serverId = String(Facade.serverId!)
        let periodId = String(self.periods[currentPeriodIndex!].period!)
        let urlString = "http://telecom.kz/api/get_bill_history?token=\(Facade.accessToken!)&client_id=\(Facade.clientId!)&period_id=\(periodId)&abonent_id=\(accountId)&server_id=\(serverId)"
        let vc = KTWebViewController(url: urlString)
        vc.title = LS("publishedCashes_pdfViewer_title")
        vc.showCloseButton()
        showViewController(vc, sender: self)
    }
    
    private func fetchNewData() {
        let currentPeriodId = periods[currentPeriodIndex!].periodId!
        if periodIdsBills.keys.contains(currentPeriodId) {
            currentBill = periodIdsBills[currentPeriodId]
        } else {
            let params = [
                "access_token": Facade.accessToken!,
                "client_id": Facade.clientId!,
                "server_id": Facade.serverId!,
                "abonent_id": Facade.accountId!,
                "oracle_id": self.periods[self.currentPeriodIndex!].periodId!
                ] as [String: AnyObject]
            
            self.loading(true)
            Facade.sharedInstance().getBillList(params, onSuccess: { (bills) in
                if !bills.isEmpty {
                    self.currentBill = bills[bills.count - 1]
                    self.periodIdsBills[self.periods[self.currentPeriodIndex!].periodId!] = bills[bills.count - 1]
                }
                }, onError: { (error) in
                    self.currentBill = nil
                }, onFinish: {
                    self.loading(false)
            })
        }
    }
    
    private func loading(enabled: Bool) {
        tableView.hidden = self.currentBill == nil ? true : enabled
        if enabled {
            indicator.startAnimating()
        } else {
            indicator.stopAnimating()
        }
    }
    
    private func currentCursorPosition() -> ItemPosition {
        return periods.count == 1 ? .FirstLast : currentPeriodIndex == periods.count - 1 ? .Last : currentPeriodIndex == 0 ? .First : .None
    }
    
    private func changeButton(itemPosition: ItemPosition) {
        rightButton.hidden = itemPosition == .Last
        leftButton.hidden = itemPosition == .First
    }
    
    private func getNumberOfRows() -> Int {
        return currentBill == nil ? 0 :  currentCursorPosition() == .Last ? AbonentInfoManager.sharedInstance.abonentInfo?.balance != nil ? 2 : 1 : 1
    }
    
    private func isShowedPayButton() -> Bool {
        return getNumberOfRows() == 2 ? true : false
    }
    
    private func createPdfButtonCell(tableView : UITableView, indexPath: NSIndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCellWithIdentifier("pdfCell", forIndexPath: indexPath)
    }
    
}

// UITableViewDataSource
extension PublishedCashesViewController {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var i = getNumberOfRows()
        return i == 0 ? 0 : i + 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        switch indexPath.row {
        case 0:
            let infoCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PublishedCashInfoCell
            infoCell.fillCell(currentBill!)
            cell = infoCell
            break
        case 1:
            if isShowedPayButton() {
                let buttonCell = tableView.dequeueReusableCellWithIdentifier(payCellIdentifier, forIndexPath: indexPath) as! PublishedCashPayCell
                buttonCell.fillCell(currentBill!)
                cell = buttonCell
            } else {
                cell = createPdfButtonCell(tableView, indexPath: indexPath)
            }
            cell.hideSeparatorLine()
            break
        case 2:
            cell = createPdfButtonCell(tableView, indexPath: indexPath)
            cell.hideSeparatorLine()
        default:
            break
        }
        cell.selectionStyle = .None
        return cell
    }
}

extension PublishedCashesViewController {
    override var localizedId: String {
        return "published_cashes"
    }
}
