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

import Foundation
import UIKit

class DeviceSettingsViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
  var loadingIndicator : UIActivityIndicatorView?
  @IBOutlet weak var tableView: UITableView!
  var device:Device!
  var deviceSettings: DeviceSettings?
  private static let labeledCellIdentifier = "labeledCell"
  private static let buttonedCellIdentifier = "buttonedCell"
  private static let switchedCellIdentifier = "switchedCell"
  let items:[[String]] = [[labeledCellIdentifier, "abonent_name"],
                          [labeledCellIdentifier, "login"],
                          [buttonedCellIdentifier, "change_credit_limit"],
                          [labeledCellIdentifier, "device"],
                        //[buttonedCellIdentifier, "mac_address"],
                          [buttonedCellIdentifier, "internet_access_password"],
                          [switchedCellIdentifier, "turbo_mode"],
                          [switchedCellIdentifier, "external_traffic"],
                          [buttonedCellIdentifier, "tariff_plan"],
                          [switchedCellIdentifier, "lock"],
                          [switchedCellIdentifier, "service_messages"],
                          [buttonedCellIdentifier, "promised_payment"],
                          [switchedCellIdentifier, "parental_control"],
                          [switchedCellIdentifier, "static_ip"],
                          [buttonedCellIdentifier, "tariff_plan_change_history"]]
  var switches: [String: UISwitch] = [String: UISwitch]()
  var buttons: [String: UIButton] = [String: UIButton]()
  var currentRequest: Request?
  var commonParams: [String: AnyObject]!
  var tariffPlans: [TariffPlanChangeHistory] = []
  
  override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    self.currentRequest?.cancel()
  }
  
  func configureRightIndicator() {
    loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    loadingIndicator!.hidesWhenStopped = true
    loadingIndicator!.color = .whiteColor()
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loadingIndicator!)
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DeviceSettingsViewController.getDeviceSettings),
                                                     name: AbonentInfoManager.NotificationNames.Update, object: AbonentInfoManager.sharedInstance)
    if AbonentInfoManager.sharedInstance.abonentInfo != nil {
      self.getDeviceSettings()
    } else {
      AbonentInfoManager.sharedInstance.updateUserInfo()
    }
    configureRightIndicator()
    configureBlueNavbar()
    addBackButtonForDefault(.whiteColor())
    localize()
    configureTableView()
  }
  
  private func configureTableView() {
    tableView.estimatedRowHeight = 100
    tableView.rowHeight = UITableViewAutomaticDimension
  }
  
  func getDeviceSettings() {
    commonParams = [
      "access_token": Facade.accessToken!,
      "client_id": Facade.clientId!,
      "server_id": Facade.serverId!,
      "abonent_id": Facade.accountId!]
    loadingIndicator?.startAnimating()
    Facade.sharedInstance().getDeviceSettings(device!.device!, onComplete: { (error, deviceSettings) -> Void in
      if let error = error {
        AlertViewUtil.showIncorrectAlert(error)
      } else if let deviceSettings = deviceSettings {
        self.deviceSettings = deviceSettings
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.reloadData()
        self.getPromisedPayment()
        self.getParentalControl()
        self.getStaticIp()
      }
      self.loadingIndicator?.stopAnimating()
    })
    
  }
  
  func getTariffPlanChangeHistory() {
    let request = GetTariffPlanChangeHistoryRequest(accessToken: Facade.accessToken, clientId: Facade.clientId, serverId: Facade.serverId, abonentId: Facade.accountId, limit: 1500, inAccountUserId: Int(deviceSettings!.accountUserId))
    if request.validateFields() {
      self.processRequest(true)
      Facade.sharedInstance().getTariffPlanChangeHistory(request.params, onSuccess: { (tariffPlans) in
        self.processRequest(false)
        self.tariffPlans = tariffPlans
        self.performSegueWithIdentifier("tariff_plan_change_history", sender: nil)
        
        print(tariffPlans)
        }, onError: { (error) in
          self.processRequest(false)
          AlertViewUtil.showErrorAlert(LS("error"), message: error)
        }, onFinish: {
          
      })
    }
  }
  
  func getParentalControl(onComplete: (() -> Void)? = nil) {
    commonParams["link_type_id"] = deviceSettings!.linkTypeId
    Facade.sharedInstance().checkParentalControl(commonParams, onSuccess: { (parentalControl) in
      if let msg = parentalControl.outMsg {
        self.deviceSettings?.parentalControlOutmsg = msg
      }
      if let code = parentalControl.outErrorCode {
        self.deviceSettings?.parentalControlOuterrcodeout = code
        self.switches["parental_control"]?.setOn(code != 1, animated: true)
      }
      }, onError: { (error) in
        print("checkParentalControl \(error)")
      }, onFinish: {
        onComplete?()
    })
  }
  
  func getStaticIp(onComplete: (() -> Void)? = nil) {
    commonParams["account_usr_id"] = deviceSettings!.accountUserId
    Facade.sharedInstance().getStaticIp(commonParams, onSuccess: { (status) in
      self.deviceSettings?.staticIpStatus = status
      self.deviceSettings?.staticIp = self.staticIpFromStatus(status)
      self.switches["static_ip"]?.setOn(status == "1", animated: true)
      }, onError: { (error) in
        print("checkStaticIp: \(error)")
      }, onFinish: {
        onComplete?()
    })
  }
  
  func getPromisedPayment(onComplete: (() -> Void)? = nil) {
    commonParams["device"] = device!.device!
    Facade.sharedInstance().getPromisedPayment(commonParams, onSuccess: { (status) in
      self.deviceSettings!.promisedPaymentStatus = status
      self.deviceSettings!.promisedPayment = self.promisedPaymentFromStatus(status)
      self.buttons["promised_payment"]?.setTitle(self.deviceSettings!.promisedPayment, forState: .Normal)
      //      self.switches[""]
      }, onError: { (error) in
        print("getPromisedPayment: \(error)")
      }, onFinish: {
        onComplete?()
    })
  }
  
    
    
  func staticIpFromStatus(status: String) -> String {
    switch status {
    case "0":
      return LS("device_settings.label.static_ip_turned_off")
    case "1":
      return LS("device_settings.label.static_ip_turned_on")
    default:
      return ""
    }
  }
  
    func showPromisePaymentActionSheet() {
        //let key = "\(parent.localizedId).label.\(localizedId)"
        
        //paymentTitleLabel.localizeWithParent(self, localizedId: "turn_on_promised_payment")
        //longSelectLabel.localizeWithParent(self, localizedId: "long_selection")
        
        let alertController = UIAlertController(title: LS("promise_payment.label.turn_on_promised_payment"), message: LS("promise_payment.label.long_selection"), preferredStyle: UIAlertControllerStyle.ActionSheet)
        alertController.addAction(UIAlertAction(title: LS("cancel"), style: UIAlertActionStyle.Cancel, handler: nil))
        alertController.addAction(UIAlertAction(title: LS("promise_payment.day"), style: UIAlertActionStyle.Default, handler: { (uiAlertActio) -> Void in
            self.sendPromisePaymentRequest(1)
        }))


        alertController.addAction(UIAlertAction(title: LS("promise_payment.5_days"), style: UIAlertActionStyle.Default, handler: { (uiAlertActio) -> Void in
            self.sendPromisePaymentRequest(5)
        }))


        self.presentViewController(alertController, animated: true, completion: nil)
    }
    
    func sendPromisePaymentRequest(length : Int) {
        let params = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            "device": device!.device!,
            "length": length
            ] as [String: AnyObject]
        PKNotification.loading(true)
        self.view.userInteractionEnabled = false
        Facade.sharedInstance().savePromisedPayment(params, onSuccess: {
            self.deviceSettings?.promisedPaymentStatus = 1
            self.deviceSettings?.promisedPayment = self.promisedPaymentFromStatus(1)
            self.dismissViewControllerAnimated(true, completion: nil)
            self.tableView.reloadData()
            }, onError: { (error) in
                AlertViewUtil.showIncorrectAlert(error)
            }, onFinish:{ () in
                PKNotification.loading(false)
                self.view.userInteractionEnabled = true
                
        })
    }
    
    
    
  func promisedPaymentFromStatus(status: Int) -> String {
    switch status {
    case 0:
      return LS("device_settings.label.payment_not_ordered")
    case 1:
      return LS("device_settings.label.payment_active")
    case 2:
      return LS("device_settings.label.payment_ordered_in_this_month")
    default:
      return ""
    }
  }
  
  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    switch segue.identifier! {
    case "tariff_plan_change_history":
      let nvc = segue.destinationViewController as! UINavigationController
      let vc = nvc.topViewController! as! TariffPlanChangeHistoryViewController
      vc.title = LS("tariffPlann.navigationPlan.title")
      vc.tariffPlans = self.tariffPlans
      break
    case "showTariffPlans":
      let nvc = segue.destinationViewController as! UINavigationController
      let vc = nvc.viewControllers[0] as! TariffPlanTableViewController
      if let tariffPlanList = deviceSettings?.megalineTariffPlanList {
        for tariffPlan in tariffPlanList {
          vc.tariffPlans.append(tariffPlan["name"] as! String)
          vc.tariffIds.append(tariffPlan["tariff_id"] as! Int)
        }
      }
      vc.mainVC = self
      break
    case "promised_payment":
        showPromisePaymentActionSheet()
//      let nvc = segue.destinationViewController as! UINavigationController
//      let vc = nvc.viewControllers[0] as! PromisePaymentViewController
//      vc.deviceSettingsVC = self
      break
    default:
      break
    }
  }
  
}

// UITableViewDataSource
extension DeviceSettingsViewController {
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
  }
  
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let item = items[indexPath.row]
    let filledCell = getCellByItem(item, indexPath: indexPath)!
    filledCell.removeLeftMargin()
    //filledCell.selectionStyle = .None
    return filledCell
  }
  
  private func getCellByItem(item: [String], indexPath: NSIndexPath) -> UITableViewCell? {
    switch item[0] {
    case DeviceSettingsViewController.labeledCellIdentifier:
      let labeledCell = tableView.dequeueReusableCellWithIdentifier(DeviceSettingsViewController.labeledCellIdentifier, forIndexPath: indexPath) as! LabeledCell
      labeledCell.fillCell(deviceSettings, property: item[1])
      return labeledCell
    case DeviceSettingsViewController.buttonedCellIdentifier:
      let buttonedCell = tableView.dequeueReusableCellWithIdentifier(DeviceSettingsViewController.buttonedCellIdentifier, forIndexPath: indexPath) as! ButtonedCell
      buttonedCell.fillCell(self, deviceSettings: deviceSettings, property: item[1])
      return buttonedCell
    case DeviceSettingsViewController.switchedCellIdentifier:
      let switchedCell = tableView.dequeueReusableCellWithIdentifier(DeviceSettingsViewController.switchedCellIdentifier, forIndexPath: indexPath) as! SwitchedCell
      switchedCell.fillCell(self, deviceSettings: deviceSettings, property: item[1])
      return switchedCell
    default: return nil
    }
  }
}

// Localized
extension DeviceSettingsViewController {
  override var localizedId:String {
    return "device_settings"
  }
}
