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

import Foundation
import UIKit

class TariffPlanTableViewController: UITableViewController {
  let reuseCellIdentifier = "cell"
  var tariffPlans:[String] = []
  var tariffIds:[Int] = []
  var mainVC: DeviceSettingsViewController?
  var selectedIndex = -1
  override func viewDidLoad() {
    super.viewDidLoad()
    addBackButtonForModal()
    //    tableView.tableFooterView = UIView(frame: CGRect.zero)
  }
  
  override func backFromModal() {
    if self.selectedIndex != -1 {
      PKNotification.loading(true)
      Facade.sharedInstance().changeTariff(self.mainVC!.deviceSettings!.device, tariffId: self.tariffIds[self.selectedIndex]) { (error, msg) -> Void in
        PKNotification.loading(false)
        if let error = error {
          AlertViewUtil.showIncorrectAlert(error)
        } else if let msg = msg {
          PKNotification.toast(msg)
          self.mainVC?.deviceSettings?.packetTypeName = self.tariffPlans[self.selectedIndex]
          self.mainVC?.tableView.reloadData()
        }
        self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
      }
    } else {
      self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
  }
  
}

//UITableViewDataSource
extension TariffPlanTableViewController {
  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(reuseCellIdentifier, forIndexPath: indexPath) as! TariffPlanCell
    cell.checkCell(indexPath.row == selectedIndex)
    cell.planTitleLabel.text = tariffPlans[indexPath.row]
    //cell.selectionStyle = .None
    return cell
  }
  
  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tariffPlans.count
  }
}

//UITableViewDelegate
extension TariffPlanTableViewController {
  override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    selectedIndex = indexPath.row
    tableView.reloadData()
  }
}
