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

import Foundation
import UIKit


public var staticTextField : UITextField?


class KeyboardUtil {
  static func changeKeyboardType(type: UIKeyboardType, textField: UITextField, leftViewRightMargin: CGFloat = 0) -> UILabel {
    //    textField.text = ""
    var textLabel : UILabel = UILabel()
    if type == .Default {
      textField.leftView?.removeFromSuperview()
      textField.leftView = nil
    } else if type == .PhonePad {
      let lView = UIView(frame: CGRect(x: 0, y: 0, width: 2, height: textField.frame.height))
      let rView = UIView(frame: CGRect(x: 0, y: 0, width: leftViewRightMargin, height: textField.frame.height))
      textLabel = UILabel(frame: CGRect(x: 2, y: 0, width: 20, height: textField.frame.height))
      textLabel.text = "+7"
      
      let leftView = UIView(frame: CGRect(x: 0, y: 0, width: textLabel.frame.width + rView.frame.width + 5, height: textField.frame.height))
      addTwoHorizontalSubviewsToView(textLabel, leftView: lView, rightView: rView, parentView: leftView)
      textField.leftView = leftView
    }
    textField.keyboardType = type
    textField.reloadInputViews()
    return textLabel
  }
  
  private static func addTwoHorizontalSubviewsToView(centerView: UIView, leftView: UIView, rightView: UIView, parentView: UIView) {
    centerView.translatesAutoresizingMaskIntoConstraints = false
    rightView.translatesAutoresizingMaskIntoConstraints = false
    leftView.translatesAutoresizingMaskIntoConstraints = false
    parentView.addSubview(centerView)
    parentView.addSubview(rightView)
    parentView.addSubview(leftView)
    let views = ["center_view": centerView, "right_view": rightView, "left_view": leftView]
    parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[left_view(\(leftView.frame.width))][center_view(\(centerView.frame.width))][right_view(\(rightView.frame.width))]|", options: [], metrics: nil, views: views))
    parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[left_view]|", options: [], metrics: nil, views: views))
    parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[center_view]|", options: [], metrics: nil, views: views))
    parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[right_view]|", options: [], metrics: nil, views: views))
  }
  
}
