//
//  BotLeftMessageCell.swift
//  kt
//
//  Created by neox on 13.07.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import UIKit

class BotLeftMessageCell: UITableViewCell, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
    
    @IBOutlet weak var container: UIView!
    @IBOutlet weak var stackView: UIStackView!
    
    private var regionTextField : UITextField!
    private var phoneTextField : UITextField!
    private var abonentTextField : UITextField!
    
    private var serverItems : [ServerItem] = []
    private var serverItem: ServerItem!
    private var serverNames: [String] = []
    private var gradePicker: UIPickerView!
    
    private var typeForm : Int = 0
    
    override func awakeFromNib() {
        super.awakeFromNib()
        container.layer.cornerRadius = 4
        container.backgroundColor = UIColor.whiteColor()
    }
    
    func bind(nodes : [BotNode]?) {
        for view in stackView.subviews {
            view.removeFromSuperview()
        }
        for node in nodes! {
            if let text = node.text, let expanded = node.expanded, let id = node.id, let formID = node.formId {
                if formID == "1" {
                    if typeForm == 0 {
                        self.showPhoneForm(UITapGestureRecognizer())
                    } else {
                        self.showAbonentForm(UITapGestureRecognizer())
                    }
                } else {
                    let label = UITextView(frame: CGRectMake(0, 0, 0, 0))
                    label.textAlignment = NSTextAlignment.Left
                    let attrStr = try! NSAttributedString(data: text.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
                    label.attributedText = attrStr
                    label.scrollEnabled = false
                    label.editable = false
                    label.font = UIFont.systemFontOfSize(14)
                    if expanded == 0 {
                        label.textColor = UIColor.blackColor()
                    } else {
                        let tap = UITapGestureRecognizer(target: self, action: #selector(BotLeftMessageCell.openChildNodesTap))
                        label.userInteractionEnabled = true
                        label.addGestureRecognizer(tap)
                        label.textColor = Color.ButtonBlueDefaultColor
                    }
                    label.tag = Int(id)!
                    self.stackView.addArrangedSubview(label)
                }
            }
        }
    }
    
    func showPhoneForm(sender:UITapGestureRecognizer) {
        
        self.typeForm = 0
        
        for view in stackView.subviews {
            view.removeFromSuperview()
        }
        
        if let pc = parentViewController as? BotViewController {
            pc.reloadTable()
        }
        
        var myMutableString = NSMutableAttributedString()
        myMutableString = NSMutableAttributedString(string: "Номер телефона или лицевой счет", attributes: [NSFontAttributeName:UIFont.systemFontOfSize(14)])
        myMutableString.addAttribute(NSForegroundColorAttributeName, value: Color.KTDefaultBlueColor, range: NSRange(location:19,length:12))
        
        let label = UILabel(frame: CGRectMake(0, 0, 140, 40))
        label.attributedText = myMutableString
        label.userInteractionEnabled = true
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(BotLeftMessageCell.showAbonentForm)))
        self.stackView.addArrangedSubview(label)
        
        phoneTextField = UITextField(frame: CGRectMake(0, 0, 140, 40))
        phoneTextField.setBottomBorder(Color.GrayTableCellSeparator)
        phoneTextField.placeholder = "Без кода города (+7)"
        phoneTextField.delegate = self
        self.stackView.addArrangedSubview(phoneTextField)
        
        let getBalanceButton = UIButton(type: .System)
        getBalanceButton.frame = CGRectMake(0, 0, 140, 40)
        getBalanceButton.setTitle("Запросить баланс", forState: UIControlState.Normal)
        getBalanceButton.userInteractionEnabled = true
        getBalanceButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(BotLeftMessageCell.getBalanceButtonTap)))
        self.stackView.addArrangedSubview(getBalanceButton)
    }
    
    func showAbonentForm(sender:UITapGestureRecognizer) {
        
        self.typeForm = 1
        
        for view in stackView.subviews {
            view.removeFromSuperview()
        }
        
        if let pc = parentViewController as? BotViewController {
            pc.reloadTable()
        }
        
        sendRequestGetServerListId()
        
        gradePicker = UIPickerView()
        gradePicker.dataSource = self
        gradePicker.delegate = self
        
        var myMutableString = NSMutableAttributedString()
        myMutableString = NSMutableAttributedString(string: "Номер телефона или лицевой счет", attributes: [NSFontAttributeName:UIFont.systemFontOfSize(14)])
        myMutableString.addAttribute(NSForegroundColorAttributeName, value: Color.KTDefaultBlueColor, range: NSRange(location:0,length:14))
        
        let label = UILabel(frame: CGRectMake(0, 0, 140, 40))
        label.attributedText = myMutableString
        label.userInteractionEnabled = true
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(BotLeftMessageCell.showPhoneForm)))
        self.stackView.addArrangedSubview(label)
        
        regionTextField = UITextField(frame: CGRectMake(0, 0, 140, 40))
        regionTextField.setBottomBorder(Color.GrayTableCellSeparator)
        regionTextField.placeholder = "Выберите регион"
        regionTextField.delegate = self
        self.stackView.addArrangedSubview(regionTextField)
        
        abonentTextField = UITextField(frame: CGRectMake(0, 0, 140, 40))
        abonentTextField.setBottomBorder(Color.GrayTableCellSeparator)
        abonentTextField.placeholder = "Лицевой счет"
        abonentTextField.delegate = self
        self.stackView.addArrangedSubview(abonentTextField)
        
        let getBalanceButton = UIButton(type: .System)
        getBalanceButton.frame = CGRectMake(0, 0, 140, 40)
        getBalanceButton.setTitle("Запросить баланс", forState: UIControlState.Normal)
        getBalanceButton.userInteractionEnabled = true
        getBalanceButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(BotLeftMessageCell.getBalanceButtonTap)))
        self.stackView.addArrangedSubview(getBalanceButton)
    }
    
    func sendRequestGetServerListId() {
        Facade.sharedInstance().getListServerId({ (serverItems) in
            self.serverItems = serverItems
            self.serverItem = serverItems[0]
            self.serverNames = self.serverItems.map({$0.name ?? ""})
            self.regionTextField.inputView = self.gradePicker
            self.regionTextField.text = self.serverNames[0]
            }, onError: { (error) in
                print(error)
        }) {
            
        }
    }
    
    func openChildNodesTap(sender:UITapGestureRecognizer) {
        if let pc = parentViewController as? BotViewController {
            pc.getChildNodes((sender.view?.tag)!)
        }
    }
    
    func getBalanceButtonTap(sender:UITapGestureRecognizer) {
        if typeForm == 0 {
            if let phoneText = phoneTextField.text {
                if phoneText.characters.count == 10 {
                    Facade.sharedInstance().getBalanceByPhone(phoneText, onSuccess: { (balance) in
                        AlertViewUtil.showMessageAlert("Текущая задолженность: \(balance)", vc: self.parentViewController!)
                        }, onError: { (error) in
                            AlertViewUtil.showMessageAlert("Ошибка получения задолженности", vc: self.parentViewController!)
                    })
                } else {
                    AlertViewUtil.showErrorAlert("Некорректный номер телефона", vc: parentViewController!)
                }
            }
        } else {
            if abonentTextField.text?.characters.count >= 4 {
                let guid = serverItem.serverId! + "-" + abonentTextField.text!
                Facade.sharedInstance().getBalanceByGuid(guid, onSuccess: { (balance) in
                    AlertViewUtil.showMessageAlert("Текущая задолженность: \(balance)", vc: self.parentViewController!)
                    }, onError: { (error) in
                        AlertViewUtil.showMessageAlert("Ошибка получения задолженности", vc: self.parentViewController!)
                })
            } else {
                AlertViewUtil.showErrorAlert("Некорректный лицевой счет", vc: parentViewController!)
            }
        }
    }
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return serverNames.count
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return serverNames[row]
    }
    
    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
        self.regionTextField.text = serverNames[row]
        self.serverItem = self.serverItems[row]
        if let pc = parentViewController as? BotViewController {
            pc.view.endEditing(true)
        }
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}
