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

import Foundation
import UIKit

class SettingButtonTableViewCell: UITableViewCell {
  @IBOutlet weak var textField: UITextField!
  @IBOutlet weak var button: UIButton!
  @IBOutlet weak var buttonWidth: NSLayoutConstraint!
  var successfullyUpdated: ((addedTrueRemovedFalse: Bool) -> Void)?
  var textFieldTitle: String = "" {
    didSet {
      textField.text = textFieldTitle
      button.setTitle(LS(textFieldTitle == "" ? "settings.add" : "settings.remove"), forState: .Normal)
      button.sizeToFit()
      buttonWidth.constant = button.frame.width
    }
  }
  var vc: LKSettingsViewController!
  
  override func awakeFromNib() {
    super.awakeFromNib()
    textField.applyUITextFieldStyle()
  }
  
  @IBAction func button_touchUpInside(sender: UIButton) {
    if button.currentTitle! == LS("settings.add") {
      if textField.text == "" {
        AlertViewUtil.showIncorrectAlert(LS("setting.email_cannot_be_blank"))
        return
      } else if !isValidEmail(textField.text!) {
        AlertViewUtil.showIncorrectAlert(LS("setting.incorrect_email"))
        return
      }
    }
    let params = [
      "access_token": Facade.accessToken!,
      "client_id": Facade.clientId!,
      "server_id": Facade.serverId!,
      "abonent_id": Facade.accountId!,
      "email":textField.text!,
      "type": button.currentTitle! == LS("settings.add") ? "ADD" : "REMOVE",
      ] as [String: AnyObject]
    PKNotification.loading(true)
    parentViewController!.view.endEditing(true)
    Facade.sharedInstance().mailNotification(params, onSuccess: { (msg) in
      print("onSuccess: \(msg)")
      self.successfullyUpdated?(addedTrueRemovedFalse: self.button.currentTitle! == LS("settings.add"))
      }, onError: { (error) in
        print(error)
      }, onFinish: { () in
        self.parentViewController!.view.endEditing(false)
        PKNotification.loading(false)
    })
  }
  
  func fillCell(vc: LKSettingsViewController) {
    self.vc = vc
    textField.delegate = vc
  }
  
  func setAvailable(av: Bool) {
    textField.userInteractionEnabled = av
  }
  
}
