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

import Foundation
import UIKit

class CustomAlertViewController: ScrolledViewController, StoryboardFetchable {
    
    static var storyboardId: String = "customAlert"
    var textFields:[UITextField] = []
    var keyboardShown = false
    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var messageLabel: UILabel!
    @IBOutlet var textFieldsContainerViewHeight: NSLayoutConstraint!
    @IBOutlet var textFieldsContainerView: UIView!
    var lastViewInContainer: UIView?
    @IBOutlet var leftButton: ModalButton!
    var leftButtonHandler: ((button: ModalButton) -> Void)?
    var rightButtonHandler: ((button: ModalButton) -> Void)?
    var keyboardDidShowCallback: ((CustomAlertViewController) -> Void)?
    
    @IBAction func leftButton_touchUpInside(sender: ModalButton) {
        leftButtonHandler?(button: sender)
        close()
    }
    
    func close() {
        ModalWindow.sharedInstance().hideLoadingView()
    }
    
    private func configureViews() {
        leftButton.titleLabel?.text = LS("cancel");
        rightButton.titleLabel?.text = LS("login.alert.send");
        titleLabel.textColor = Color.DarkColorForText
        messageLabel.textColor = Color.DarkColorForText
    }
    
    @IBOutlet var rightButton: ModalButton!
    @IBAction func rightButton_touchUpInside(sender: ModalButton) {
        rightButtonHandler?(button: sender)
    }
    var lastViewBottomConstraint: NSLayoutConstraint?
    @IBOutlet var messageLabelTopConstraint: NSLayoutConstraint!
    @IBOutlet var messageLabelBottomConstraint: NSLayoutConstraint!
    var originalOrigin: CGPoint?
    
    // MARK: Keyboard action
    override func keyboardDidShow(notification: NSNotification) {
        
        tapGestureRecognizer.enabled = true
        let info = notification.userInfo!
        var kbRect = info[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue
        kbRect = view.convertRect(kbRect, fromView: nil)
        keyboardDidShowCallback?(self)
        originalOrigin = view.frame.origin
        //    if keyboardShown {
        //      originalOrigin = CGPoint(x: 0, y: view.frame.origin.y + kbRect.height - 75)
        //    }
        if !keyboardShown {
            view.frame.origin = CGPoint(x: view.frame.origin.x, y: kbRect.origin.y - (kbRect.height + 95))
            keyboardShown = true
        }
    }
    
    func createTextField() -> GreyRoundFrameTextField {
        let textField = GreyRoundFrameTextField(frame: CGRect(x: 0, y: 0, width: 0, height: 31))
        //    textField.borderStyle = UITextBorderStyle.RoundedRect
        return textField
    }
    
    override func keyboardWillBeHidden(notification: NSNotification) {
        tapGestureRecognizer.enabled = false
        keyboardShown = false
        view.frame.origin = CGPoint(x: view.frame.origin.x, y: originalOrigin == nil ? 0 : originalOrigin!.y)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureViews()
        self.keyboardShown = CustomKeyboardManager.sharedInstance().isVisible
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if CustomKeyboardManager.sharedInstance().isVisible {
            let info = CustomKeyboardManager.sharedInstance().notification!.userInfo!
            //      let info = notification.userInfo!
            var kbRect = info[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue
            kbRect = view.convertRect(kbRect, fromView: nil)
            originalOrigin = view.frame.origin
            view.frame.origin = CGPoint(x: view.frame.origin.x, y: 25)
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        resizeScrollViewToFitSubviews()
        rightButton.roundCorners([.BottomRight], radius: 7)
    }
    
    func addTitleAndMessage(title: String? = nil, msg: String? = nil) {
        titleLabel.text = title
        titleLabel.sizeToFit()
        messageLabel.text = ""
        if let msg = msg {
            messageLabel.text = msg
            messageLabel.sizeToFit()
        } else {
            messageLabelTopConstraint.constant = 0
        }
    }
    
    func addButtonTitles(leftButtonTitle: String? = LS("cancel"), rightButtonTitle: String? = "Ok") {
        leftButton.setTitle(leftButtonTitle, forState: .Normal)
        rightButton.setTitle(rightButtonTitle, forState: .Normal)
    }
    
    func addButtonHandlers(leftButtonHandler: ((button: ModalButton) -> Void)? = nil, rightButtonHandler: ((button: ModalButton) -> Void)? = nil) {
        self.leftButtonHandler = leftButtonHandler
        self.rightButtonHandler = rightButtonHandler
    }
    
    func addView(someView: UIView) {
        someView.translatesAutoresizingMaskIntoConstraints = false
        textFieldsContainerView.addSubview(someView)
        
        textFieldsContainerView.addConstraint(NSLayoutConstraint(item: someView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: textFieldsContainerView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
        textFieldsContainerView.addConstraint(NSLayoutConstraint(item: someView, attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: textFieldsContainerView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
        textFieldsContainerView.addConstraint(NSLayoutConstraint(item: someView, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: textFieldsContainerView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
        //    textFieldsContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[some_view(\(someView.frame.width))]|", options: [], metrics: nil, views: ["some_view": someView]))
        textFieldsContainerView.addConstraint(NSLayoutConstraint(item: someView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: someView.frame.height))
        if let lastTextFieldBottomConstraint = lastViewBottomConstraint {
            textFieldsContainerView.removeConstraint(lastTextFieldBottomConstraint)
        }
        if let lastViewInContainer = lastViewInContainer {
            textFieldsContainerView.addConstraint(NSLayoutConstraint(item: someView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: lastViewInContainer, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 20))
        } else {
            textFieldsContainerView.addConstraint(NSLayoutConstraint(item: someView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: textFieldsContainerView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        }
        lastViewBottomConstraint = NSLayoutConstraint(item: someView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: textFieldsContainerView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -15)
        textFieldsContainerView.addConstraint(lastViewBottomConstraint!)
        textFieldsContainerView.resizeToFitSubviews()
        lastViewInContainer = someView
        resizeScrollViewToFitSubviews()
    }
    
    func addTextField(textField: GreyRoundFrameTextField, isSecure: Bool = false) {
        textFieldsContainerView.addSubview(textField)
        textField.delegate = self
        textField.secureTextEntry = isSecure
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.setBottomBorder(Color.GrayTableCellSeparator)
        textFieldsContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[text_field]|", options: [], metrics: nil, views: ["text_field": textField]))
        if let lastTextFieldBottomConstraint = lastViewBottomConstraint {
            textFieldsContainerView.removeConstraint(lastTextFieldBottomConstraint)
        }
        if let lastViewInContainer = lastViewInContainer {
            textFieldsContainerView.addConstraint(NSLayoutConstraint(item: textField, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: lastViewInContainer, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 15))
        } else {
            textFieldsContainerView.addConstraint(NSLayoutConstraint(item: textField, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: textFieldsContainerView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        }
        lastViewBottomConstraint = NSLayoutConstraint(item: textField, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: textFieldsContainerView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -15)
        textFieldsContainerView.addConstraint(lastViewBottomConstraint!)
        textFields.append(textField)
        lastViewInContainer = textField
        textFieldsContainerView.resizeToFitSubviews()
        resizeScrollViewToFitSubviews()
    }
    
    func fillAndShowAlert(width: CGFloat, height: CGFloat, presentingVC: UIViewController, closure: (alertVC: CustomAlertViewController) -> Void) {
        showModally(self, presentingVC: presentingVC, width: width, height: height, cornerRadius: 7)
        closure(alertVC: self)
    }
    
    override func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let textFieldText: NSString = textField.text ?? ""
        let txtAfterUpdate = textFieldText.stringByReplacingCharactersInRange(range, withString: string)
        
        if ( textField.tag == 101 ) {
            textField.text = (getFormattedPhone(txtAfterUpdate))
            return false
        } else {
            return true
        }
    }
    
}
