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

import Foundation
import UIKit

class ButtonedCell: UITableViewCell, UITextFieldDelegate {
    @IBOutlet weak var someButtonHeight: NSLayoutConstraint!
    @IBOutlet weak var buttonBackgroundLabel: UILabel!
    @IBOutlet weak var someLabel: UILabel!
    @IBOutlet weak var someButton: UIButton!
    var buttonClickHandler: ((sender: UIButton) -> Void)? = nil
    var vc: DeviceSettingsViewController!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        someButton.titleLabel?.numberOfLines = 0
        someButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
        someButton.titleLabel?.textAlignment = NSTextAlignment.Center
        someLabel.textColor = Color.DarkColorForText
        self.contentView.bringSubviewToFront(self.someButton)
    }
    
    @IBAction func button_touchUpInside(sender: AnyObject) {
        buttonClickHandler?(sender: sender as! UIButton)
    }
    
    func fillCell(vc: DeviceSettingsViewController, deviceSettings: DeviceSettings?, property: String) {
        vc.buttons[property] = someButton
        self.vc = vc
        someLabel.localizeWithParent(self, localizedId: property)
        setButtonValues(deviceSettings, property: property)
        setButtonHandlers(deviceSettings,property: property)
    }
    
    func setButtonTitle(text: String?) {
        buttonBackgroundLabel.setTextAndSizeToFit(text)
        someButton.setTitle(text, forState: .Normal)
    }
    
    private func setButtonValues(deviceSettings: DeviceSettings?, property: String) {
        switch property {
        case "tariff_plan_change_history":
            setButtonTitle(LS("device_settings.button.look"))
            break
        case "change_credit_limit":
            setButtonTitle(deviceSettings?.limitInfo)
            break
        case "mac_address":
            setButtonTitle(deviceSettings?.mac)
            someButton.enabled = false
            someButton.setTitleColor(someButton.tintColor.colorWithAlphaComponent(0.3), forState: .Normal)
            break
        case "internet_access_password":
            setButtonTitle(LocalizedString("device_settings.label.change"))
            break
        case "tariff_plan":
            if let tariffPlans = deviceSettings?.megalineTariffPlanList where tariffPlans.isEmpty {
                someButton.setTitleColor(Color.DarkColorForText, forState: .Normal)
                //        someButton.enabled = false
            }
            setButtonTitle(deviceSettings?.packetTypeName)
            break
        case "promised_payment":
            someButton.setTitle(deviceSettings?.promisedPayment, forState: .Normal)
            //      someButton.enabled = deviceSettings?.promisedPaymentStatus == 0
            break
        default: break
        }
    }
    
    private func setButtonHandlers(deviceSettings: DeviceSettings?, property: String) {
        switch property {
        case "tariff_plan_change_history":
            buttonClickHandler = { (sender) in
                self.vc.getTariffPlanChangeHistory()
            }
            break
        case "change_credit_limit":
            buttonClickHandler = { (sender) in
                let customAlertVC = CustomAlertViewController.fromStoryboard()
                customAlertVC.fillAndShowAlert(300, height: UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 260 : 170, presentingVC: UIApplication.sharedApplication().keyWindow!.rootViewController!) { (alertVC) -> Void in
                    alertVC.addButtonHandlers({ (button) -> Void in
                        //            todo: fix error
                        }, rightButtonHandler: { (button) -> Void in
                            let request = ChangeCreditLimitRequest(accessToken: Facade.accessToken!, clientId: Facade.clientId!, serverId: Facade.serverId!, abonentId: "\(Facade.accountId!)", limit: alertVC.textFields[0].text, inAccountUserId: self.vc.deviceSettings!.accountUserId)
                            guard request.validateFields() else { AlertViewUtil.showAlert(LS("incorrect_value")); return }
                            PKNotification.loading(true)
                            Facade.sharedInstance().changeCreditLimit(request.params, onSuccess: {
                                self.someButton.setTitle(request.limit, forState: .Normal)
                                alertVC.close()
                                self.vc.navigationController!.view.endEditing(true)
                                //                AlertViewUtil.showAlert(LS("device_settings.label.success_credit_limit"))
                                }, onError: { (error) in
                                    AlertViewUtil.showErrorAlert(error, vc: UIApplication.sharedApplication().keyWindow!.rootViewController!)
                                }, onFinish: {
                                    PKNotification.loading(false)
                            })
                    })
                    alertVC.addTitleAndMessage(LocalizedString("device_settings.label.change_credit_limit"), msg: LocalizedString("device_settings.label.type_new_credit_limit"))
                    alertVC.addButtonTitles(rightButtonTitle: LocalizedString("device_settings.label.save"))
                    let textField = alertVC.createTextField()
                    if let limitInfo = deviceSettings?.limitInfo {
                        var convertedLimitInfo = limitInfo.stringByReplacingOccurrencesOfString("\\(.+", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
                        textField.text = convertedLimitInfo
                        textField.setBottomBorder(Color.GrayTableCellSeparator)
                        textField.delegate = self
                    }
                    alertVC.addTextField(textField)
                    
                }
            }
            break
        case "mac_address":
            buttonClickHandler = { (sender) in
                let alert = UIAlertController(title: LS("device_settings.label.change_mac_address"), message: LS("device_settings.label.type_new_mac_address"), preferredStyle: UIAlertControllerStyle.Alert)
                alert.addTextFieldWithConfigurationHandler({ (textField) in
                    //          textField.borderStyle = .RoundedRect
                    textField.placeholder = "_-_-_-_-_-_-_"
                    textField.setBottomBorder(Color.GrayTableCellSeparator)
                    textField.delegate = self
                    textField.becomeFirstResponder()
                })
                alert.addAction(UIAlertAction(title: LS("cancel"), style: .Cancel, handler: nil))
                alert.addAction(UIAlertAction(title: LS("device_settings.change"), style: UIAlertActionStyle.Default, handler: { (alertAction) in
                    if isValidMacAddress(alert.textFields![0].text!) {
                    } else {
                        alert.view.endEditing(true)
                        AlertViewUtil.showMessageAlert(LS("login.label.incorrect_data"), vc: UIApplication.sharedApplication().keyWindow!.rootViewController!)
                    }
                }))
                //        UIApplication.sharedApplication().keyWindow!.rootViewController!.presentViewController(alert, animated: true, completion: nil)
                //        for textfield: UIView in alert.textFields! {
                //          var container: UIView = textfield.superview!
                //          var effectView: UIView = container.superview!.subviews[0]
                //          container.backgroundColor = UIColor.clearColor()
                //          effectView.removeFromSuperview()
                //        }
                
                // ------------------------------------------------------------------------
                
                //        let customAlertVC = CustomAlertViewController.fromStoryboard()
                //        customAlertVC.fillAndShowAlert(300, height: 200, presentingVC: self.vc.navigationController!) { (alertVC) -> Void in
                //          alertVC.addButtonHandlers({ (button) -> Void in
                //
                //            }, rightButtonHandler: { (button) -> Void in
                //              if isValidMacAddress(alertVC.textFields[0].text!) {
                //
                //              } else {
                //                AlertViewUtil.showIncorrectAlert()
                //              }
                //              //        todo: спросить начсет мак адреса у сани
                //          })
                //          alertVC.addTitleAndMessage(LS("device_settings.label.change_mac_address"), msg: LS("device_settings.label.type_new_mac_address"))
                //          alertVC.addButtonTitles(rightButtonTitle: LS("device_settings.change"))
                //
                //          let textField = alertVC.createTextField()
                //          textField.placeholder = "_-_-_-_-_-_-_"
                //          alertVC.addTextField(textField)
                //          textField.becomeFirstResponder()
                //        }
            }
            break
        case "internet_access_password":
            buttonClickHandler = { (sender) in
                let customAlertVC = CustomAlertViewController.fromStoryboard()
                customAlertVC.fillAndShowAlert(300, height: 280, presentingVC: UIApplication.sharedApplication().keyWindow!.rootViewController!, closure: { (alertVC) -> Void in
                    customAlertVC.addTitleAndMessage(LocalizedString("device_settings.label.change_internet_access_password"))
                    customAlertVC.addButtonTitles(rightButtonTitle: LocalizedString("device_settings.change"))
                    for i in 0..<3 {
                        let textField = alertVC.createTextField()
                        var localizedId = ""
                        switch i {
                        case 0:
                            localizedId = "old_password"
                            break
                        case 1:
                            localizedId = "new_password"
                            break
                        case 2:
                            localizedId = "repeat_new_password"
                            break
                        default:
                            break
                        }
                        textField.localizeWithParent(self, localizedId: localizedId)
                        textField.setBottomBorder(Color.GrayTableCellSeparator)
                        textField.delegate = self
                        customAlertVC.addTextField(textField, isSecure: true)
                    }
                    customAlertVC.textFields[0].becomeFirstResponder()
                    customAlertVC.addButtonHandlers({ (button) -> Void in
                        
                        }, rightButtonHandler: { (button) -> Void in
                            let request = ChangeInternetAccessPasswordRequest(accessToken: Facade.accessToken!, clientId: Facade.clientId!, serverId: Facade.serverId!, abonentId: self.vc.deviceSettings!.accountUserId, oldPassword: alertVC.textFields[0].text, newPassword: alertVC.textFields[1].text, newPasswordRepeat: alertVC.textFields[2].text)
                            if !request.validateFields() {
                                AlertViewUtil.showIncorrectAlert()
                            } else {
                                self.parentViewController!.processRequest(true)
                                Facade.sharedInstance().changeInternetAccessPassword(request.params, onSuccess: {
                                    PKNotification.success(nil)
                                    }, onError: { (error) in
                                        AlertViewUtil.showErrorAlert(error, vc: UIApplication.sharedApplication().keyWindow!.rootViewController!)
                                    }, onFinish: {
                                        self.parentViewController!.processRequest(false)
                                })
                                
                            }
                    })
                })
            }
            break
        case "tariff_plan":
            buttonClickHandler = { (sender) in
                if let tariffPlans = deviceSettings?.megalineTariffPlanList where !tariffPlans.isEmpty {
                    self.vc.performSegueWithIdentifier("showTariffPlans", sender: nil)
                }
            }
            break
        case "promised_payment":
            buttonClickHandler = { (sender) in
                //        first solution:
                self.vc.showPromisePaymentActionSheet()
                //self.vc.performSegueWithIdentifier("promised_payment", sender: nil)
                //        alternative solution:
                //        let alert = CustomAlertViewController.fromStoryboard()
                //        alert.fillAndShowAlert(300, height: 280, presentingVC: self.vc.navigationController!, closure: { (alertVC) in
                //          let pickerView = UIPickerView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 250, height: 100)))
                //          alertVC.addView(pickerView)
                //          alert.addButtonTitles(LS("cancel"), rightButtonTitle: LS("settings.save"))
                //          alertVC.addButtonHandlers({ (button) in
                //            alert.close()
                //            }, rightButtonHandler: { (button) in
                //          })
                //        })
            }
            break
        default: break
        }
        
    }
    
}

// UITextFieldDelegate
extension ButtonedCell {
    func textFieldDidBeginEditing(textField: UITextField) {
        //    activeField = textField
        textField.setBottomBorder(Color.BlueButtonColor)
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        //    activeField = nil
        textField.setBottomBorder(Color.GrayTableCellSeparator)
    }
}

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