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

import Foundation
import UIKit

class SubscribeHistoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    let cellIdentifier = "cell"
    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var rightButton: UIButton!
    @IBOutlet weak var periodLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var indicator: UIActivityIndicatorView!
    @IBOutlet weak var noDataLabel: UILabel!
    var currentSubscribePeriod: SubscribePeriod? {
        didSet {
            if let traffics = currentSubscribePeriod?.traffics where traffics.isEmpty {
                noDataLabel.hidden = false
            } else {
                noDataLabel.hidden = true
            }
        }
    }
    var subscribeMonth: SubscribeMonth?
    var device: Device?
    var periodIdsStatistics: [Int: SubscribePeriod] = [Int: SubscribePeriod]()
    var currentPeriodIndex: Int? {
        didSet {
            if let currentPeriodIndex = currentPeriodIndex {
                periodLabel.text = self.subscribeMonth!.periods[currentPeriodIndex].name
                self.fetchNewData()
            }
        }
    }
    var noData = false {
        didSet {
            self.noDataLabel.hidden = !noData
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localizeViews()
        self.configureBlueNavbar()
        self.addBackButtonForDefault(.whiteColor())
    }
    
    func localizeViews() {
        localize()
        self.noDataLabel.setTextAndSizeToFit(LS("no_data"))
    }
    
    func configureViews() {
        configureTableView()
        periodLabel.textColor = Color.DarkColorForText
        noDataLabel.textColor = Color.DarkColorForText
        self.view.bringSubviewToFront(noDataLabel)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureViews()
        let params = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            "device": device!.device!
            ] as [String: AnyObject]
        Facade.sharedInstance().subscribeHistoryForMonth(params, onSuccess: { (subscribeMonth) in
            self.subscribeMonth = subscribeMonth
            self.currentPeriodIndex = self.subscribeMonth?.periods.count > 0 ? self.subscribeMonth!.periods.count - 1 : nil
            }, onError: { (error) in
                self.noData = true
                AlertViewUtil.showIncorrectAlert(error)
            }, onFinish: {() in
                
        })
    }
    
    private func changePeriod(isNext: Bool) {
        if let currentPeriodIndex = currentPeriodIndex {
            if isNext {
                self.currentPeriodIndex = currentPeriodIndex < self.subscribeMonth!.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)
    }
    
    private func currentCursorPosition() -> ItemPosition {
        return self.subscribeMonth!.periods.count == 1 ? .FirstLast : currentPeriodIndex == self.subscribeMonth!.periods.count - 1 ? .Last : currentPeriodIndex == 0 ? .First : .None
    }
    
    private func changeButton(itemPosition: ItemPosition) {
        rightButton.hidden = itemPosition == .Last
        leftButton.hidden = itemPosition == .First
    }
    
    private func loading(enabled: Bool) {
        tableView.hidden = self.currentSubscribePeriod == nil ? true : enabled
        noDataLabel.hidden = true
        if enabled {
            indicator.startAnimating()
        } else {
            indicator.stopAnimating()
        }
    }
    
    private func fetchNewData() {
        changeButton(currentCursorPosition())
        guard let currentPeriodId = subscribeMonth!.periods[currentPeriodIndex!].periodId else {
            self.loading(false)
            return
        }
        if periodIdsStatistics.keys.contains(currentPeriodId) {
            currentSubscribePeriod = periodIdsStatistics[currentPeriodId]
        } else {
            let params = [
                "access_token": Facade.accessToken!,
                "client_id": Facade.clientId!,
                "server_id": Facade.serverId!,
                "abonent_id": Facade.accountId!,
                "period_id": self.subscribeMonth!.periods[self.currentPeriodIndex!].periodId!
                ] as [String: AnyObject]
            
            self.loading(true)
            Facade.sharedInstance().subscribeHistoryForPeriod(params, onSuccess: { (subscribePeriod) in
                self.currentSubscribePeriod = subscribePeriod
                self.periodIdsStatistics[self.subscribeMonth!.periods[self.currentPeriodIndex!].periodId!] = subscribePeriod
                }, onError: { (error) in
                    self.currentSubscribePeriod = nil
                }, onFinish: {
                    self.loading(false)
            })
        }
    }
    
    private func configureTableView() {
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 280
    }
}

// UITableViewDataSource
extension SubscribeHistoryViewController {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return currentSubscribePeriod != nil ? currentSubscribePeriod!.traffics.count : 0
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SubscribeHistoryCell
        cell.fillCell(currentSubscribePeriod!.traffics[indexPath.row])
        return cell
    }
}

extension SubscribeHistoryViewController {
    override var localizedId: String {
        return "subscribe_history"
    }
}
