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

import Foundation
import UIKit

class SwitchedCell: UITableViewCell {
  @IBOutlet weak var someLabel: UILabel!
  @IBOutlet weak var someSwitch: UISwitch!
  var vc: DeviceSettingsViewController!
  var switchChangedHandler: ((sender: UISwitch) -> Void)? = nil
  
  @IBAction func switch_touchUpInside(sender: UISwitch) {
    print("switch_touchUpInside")
  }
  
  @IBAction func switch_editingDidBegin(sender: UISwitch) {
    print("switch_editingDidBegin")
  }
  
  @IBAction func switch_touchDown(sender: UISwitch) {
    print("switch_touchDown")
  }
  
  @IBAction func switch_valueChanged(sender: UISwitch) {
    print("on: \(sender.on)")
    switchChangedHandler?(sender: sender)
  }
  
  func fillCell(vc: DeviceSettingsViewController, deviceSettings: DeviceSettings?, property: String) {
    vc.switches[property] = someSwitch
    self.vc = vc
    someLabel.textColor = Color.DarkColorForText
    someLabel.localizeWithParent(self, localizedId: property)
    setSwitchHandlers(deviceSettings, property: property)
    setSwitchValues(deviceSettings, property: property)
  }
  
  private func setSwitchValues(deviceSettings: DeviceSettings?, property: String) {
    switch property {
    case "turbo_mode":
      if let deviceSettings = deviceSettings {
        switch deviceSettings.turboInfo {
        case "-1":
          someSwitch.enabled = false
          someSwitch.setOn(false, animated: false)
          break
        case "0":
          someSwitch.enabled = false
          someSwitch.setOn(false, animated: false)
          break
        case "1":
          someSwitch.enabled = false
          someSwitch.setOn(true, animated: false)
          break
        case "2":
          someSwitch.enabled = true
          someSwitch.setOn(false, animated: false)
          break
        default:
          break
        }
        break
      }
    case "external_traffic":
      someSwitch.setOn(vc.deviceSettings!.isExternalTraffic == "1", animated: false)
      break
    case "lock":
      someSwitch.setOn(vc.deviceSettings!.isBlock != "F", animated: true)
      someSwitch.enabled = false
      break
    case "service_messages":
      someSwitch.setOn(vc.deviceSettings?.message != nil, animated: false)
      someSwitch.enabled = false
      break
    case "parental_control":
      someSwitch.setOn(vc.deviceSettings!.parentalControlOuterrcodeout != 1, animated: true)
      break
    case "static_ip":
      someSwitch.setOn(vc.deviceSettings!.staticIpStatus == "1", animated: true)
      break
    //      "device_settings.label.static_ip" = "Статический IP-адрес";
    default: break
    }
  }
  
  private func setSwitchHandlers(deviceSettings: DeviceSettings?, property: String) {
    switch property {
    case "turbo_mode":
      switchChangedHandler = { (sender) in
        //        "access_token": "AMDIOFGYWVSCOJJJFPNTSRHITFVE",
        //        "client_id": "070940cb6e47c9fd84",
        //        "server_id": 17,
        //        "abonent_id":2261416,
        //        "device":101640
        let params = [
          "access_token": Facade.accessToken!,
          "client_id": Facade.clientId!,
          "server_id": Facade.serverId!,
          "abonent_id": self.vc.deviceSettings!.accountUserId,
          "device": Int(self.vc.device!.device!)!
          ] as [String: AnyObject]
        self.parentViewController!.processRequest(true)
        Facade.sharedInstance().setTurboTraffic(params, onSuccess: {
          self.parentViewController!.processRequest(false)
          sender.enabled = false
          }, onError: { (error) in
            AlertViewUtil.showIncorrectAlert(error)
            sender.setOn(!sender.on, animated: false)
            self.parentViewController!.processRequest(false)
        })
      }
      break
    case "external_traffic":
      switchChangedHandler = { (sender) in
        let params = [
          "access_token": Facade.accessToken!,
          "client_id": Facade.clientId!,
          "server_id": Facade.serverId!,
          "abonent_id": self.vc.deviceSettings!.accountUserId,
          "flag": sender.on ? 1 : 0,
          "in_link_type_id": Int(self.vc.deviceSettings!.linkTypeId)!,
          "in_packet_type_id" : Int(self.vc.deviceSettings!.packetTypeId)!
          ] as [String: AnyObject]
        self.parentViewController!.processRequest(true)
        Facade.sharedInstance().setExtTraffic(params, onSuccess: {
          self.parentViewController!.processRequest(false)
          }, onError: { (error) in
            AlertViewUtil.showIncorrectAlert(error)
            sender.setOn(!sender.on, animated: false)
            self.parentViewController!.processRequest(false)
        })
      }
      break
    case "lock":
      switchChangedHandler = { (sender) in
        print("lock")
      }
      break
    case "service_messages":
      switchChangedHandler = { (sender) in
        print("service_messages")
      }
    case "parental_control":
      switchChangedHandler = { (sender) in
        let msg = LS(sender.on ? "device_settings.label.parental_control_turn_on_message" : "device_settings.label.parental_control_turn_off_message")
        let alert = UIAlertController(title: LS(sender.on ? "device_settings.label.parental_control_turn_on" : "device_settings.label.parental_control_turn_off"), message: msg, preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: LS("cancel"), style: .Cancel, handler: { (alertAction) in
          sender.setOn(!sender.on, animated: false)
        }))
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (alertAction) in
          var params = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": self.vc.deviceSettings!.accountUserId,
            "device": Int(self.vc.device!.device!)!,
            "link_type_id": Int(self.vc.deviceSettings!.linkTypeId)!,
            ] as [String: AnyObject]
          
          self.parentViewController!.processRequest(true)
          if sender.on {
            params["email"] = AbonentInfoManager.sharedInstance.abonentInfo!.email
            Facade.sharedInstance().addSi(params, onSuccess: {
              sender.setOn(sender.on, animated: false)
              }, onError: { (error) in
                AlertViewUtil.showIncorrectAlert(error)
                sender.setOn(!sender.on, animated: false)
              }, onFinish: {
                self.parentViewController!.processRequest(false)
            })
          } else {
            Facade.sharedInstance().removeSi(params, onSuccess: {
              sender.setOn(sender.on, animated: false)
              }, onError: { (error) in
                alert.dismissViewControllerAnimated(false, completion: nil)
                AlertViewUtil.showIncorrectAlert(error)
                sender.setOn(!sender.on, animated: false)
              }, onFinish: {
                self.parentViewController!.processRequest(false)
            })
          }
        }))
        self.vc.presentViewController(alert, animated: true, completion: nil)
      }
      break
    case "static_ip":
      switchChangedHandler = { (sender) in
        
        let params = [
          "access_token": Facade.accessToken!,
          "client_id": Facade.clientId!,
          "server_id": Facade.serverId!,
          "abonent_id": Facade.accountId!,
          "in_device": self.vc.device!.device!,
          "in_link_type_id": Int(self.vc.deviceSettings!.linkTypeId)!,
          ] as [String: AnyObject]
        
        self.parentViewController!.processRequest(true)
        self.vc.currentRequest = Facade.sharedInstance().changeStaticIp(params, onSuccess: { (msg) in
          AlertViewUtil.showIncorrectAlert(msg)
          self.setOppositeStaticIp()
          sender.setOn(self.vc.deviceSettings!.staticIpStatus == "1", animated: false)
          }, onError: { (error) in
            AlertViewUtil.showIncorrectAlert(error)
            sender.setOn(self.vc.deviceSettings!.staticIpStatus == "1", animated: false)
          }, onFinish: {
            self.parentViewController!.processRequest(false)
        })
      }
      break
    default: break
    }
  }
  
  func setOppositeStaticIp() {
    self.vc.deviceSettings!.staticIpStatus = self.vc.deviceSettings!.staticIpStatus == "0" ? "1" : "0"
  }
}

extension SwitchedCell : LocalizedParent {
  var localizedId:String {
    return "device_settings"
  }
}
