
// Created by Alexander Zalutskiy on 04.08.15.
// Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit

private var maxLengths = [UITextField: Int]()

extension UITextField {
  
  //  func setBottomBorder(color: UIColor)
  //  {
  //    self.borderStyle = UITextBorderStyle.None
  //    let border = CALayer()
  //    let width = CGFloat(1.0)
  //    border.borderColor = color.CGColor
  //    border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
  //
  //    border.borderWidth = width
  //    self.layer.addSublayer(border)
  //    self.layer.masksToBounds = true
  //  }
  
  //  public override func awakeFromNib() {
  //    super.awakeFromNib()
  //    setBottomBorder(Color.GrayTableCellSeparator)
  //  }
  
  func setBottomBorder(borderColor: UIColor)
  {
    self.borderStyle = UITextBorderStyle.None
    self.backgroundColor = UIColor.clearColor()
    let width: CGFloat = 1
    if let index = self.subviews.indexOf({$0.tag == -777}) {
      self.subviews[index].removeFromSuperview()
    }
    let borderYPos = self.frame.height - width
    let borderLine = UIView(frame: CGRectMake(0, borderYPos, self.frame.width, width))
    borderLine.backgroundColor = borderColor
    borderLine.tag = -777
    self.addSubview(borderLine)
    
    borderLine.translatesAutoresizingMaskIntoConstraints = false
    let views = ["border": borderLine]
    self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[border]|", options: [], metrics: nil, views: views))
    self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(borderYPos < 0 ? 0 : borderYPos)-[border(\(width))]|", options: [], metrics: nil, views: views))
    //    self.bringSubviewToFront(borderLine)
  }
  
  // 3
  @IBInspectable var maxLength: Int {
    get {
      // 4
      guard let length = maxLengths[self] else {
        return Int.max
      }
      return length
    }
    set {
      maxLengths[self] = newValue
      // 5
      addTarget(
        self,
        action: #selector(limitLength),
        forControlEvents: UIControlEvents.EditingChanged
      )
    }
  }
  
  func limitLength(textField: UITextField) {
    // 6
    guard let prospectiveText = textField.text
      where prospectiveText.characters.count > maxLength else {
        return
    }
    
    let selection = selectedTextRange
    // 7
    text = prospectiveText.substringWithRange(
      Range<String.Index>(prospectiveText.startIndex ..< prospectiveText.startIndex.advancedBy(maxLength))
    )
    selectedTextRange = selection
  }
  
}
