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

import Foundation
import UIKit

class DetalizationViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
  @IBOutlet weak var leftButton: UIButton!
  @IBOutlet weak var rightButton: UIButton!
  @IBOutlet weak var indicator: UIActivityIndicatorView!
  @IBOutlet weak var periodLabel: UILabel!
  @IBOutlet weak var tableView: UITableView!
  let reuseCellIdentifier = "cell"
  var periods: [AltelPeriod] = []
  var currentPeriodIndex: Int? {
    didSet {
      periodLabel.text = self.periods[currentPeriodIndex!].name
      self.changeButton(currentCursorPosition())
      self.fetchNewData()
    }
  }
  var detalizations: [String: [AltelDetalization]] = [String: [AltelDetalization]]()
  var currentDetalizations: [AltelDetalization] = [] {
    didSet {
      self.tableView.hidden = self.currentDetalizations.isEmpty
      self.tableView.reloadData()
    }
  }
  var phone: String?
  
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    localize()
  }
  
  private func fetchNewData() {
    if detalizations.keys.contains(periods[currentPeriodIndex!].periodId) {
      currentDetalizations = detalizations[periods[currentPeriodIndex!].periodId]!
    } else {
      let params = [
        "access_token": Facade.accessToken!,
        "client_id": Facade.clientId!,
        "server_id": Facade.serverId!,
        "abonent_id": Facade.accountId!,
        "phone": phone!,
        "period_id": periods[currentPeriodIndex!].periodId
        ] as [String: AnyObject]
      self.loading(true)
      Facade.sharedInstance().getAltelDetalization(params, onError: { (error) in
        AlertViewUtil.showIncorrectAlert(error)
        }, onSuccess: { (altelDetalizations) in
          self.detalizations[self.periods[self.currentPeriodIndex!].periodId] = altelDetalizations
          self.currentDetalizations = altelDetalizations
        }, onFinish: {() in
          self.loading(false)
      })
    }
    tableView.reloadData()
  }
  
  private func loading(enabled: Bool) {
    tableView.hidden = self.currentDetalizations.isEmpty ? true : enabled
    if enabled {
      indicator.startAnimating()
    } else {
      indicator.stopAnimating()
    }
  }
  
  private func changePeriod(isNext: Bool) {
    if isNext {
      currentPeriodIndex = currentPeriodIndex < periods.count - 1 ? currentPeriodIndex! + 1 : currentPeriodIndex!
    } else {
      currentPeriodIndex = currentPeriodIndex > 0 ? currentPeriodIndex! - 1 : currentPeriodIndex!
    }
  }
  
  @IBAction func left_touchUpInside(sender: UIButton) {
    changePeriod(false)
  }
  
  @IBAction func right_touchUpInside(sender: UIButton) {
    changePeriod(true)
  }
  
  private func configureTableView() {
    tableView.estimatedRowHeight = 130
    tableView.rowHeight = UITableViewAutomaticDimension
  }
  
  func configureViews() {
    configureTableView()
    periodLabel.textColor = Color.DarkColorForText
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    configureBlueNavbar()
    configureViews()
    Facade.sharedInstance().getAltelPeriods({ (error) in
      AlertViewUtil.showIncorrectAlert(error)
    }) { (altelPeriods) in
      self.periods = altelPeriods
      self.currentPeriodIndex = self.periods.count - 1
      self.fetchNewData()
    }
  }
  
  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
  }
  
}

// UITableViewDataSource
extension DetalizationViewController {
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return currentDetalizations.count
  }
  
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(reuseCellIdentifier, forIndexPath: indexPath) as! DetalizationCell
    cell.fillCell(currentDetalizations[indexPath.row])
    //cell.selectionStyle = .None
    return cell
  }
}

extension DetalizationViewController {
  override var localizedId: String {
    return "altel_detalization"
  }
}
