//
//  UILabel+Util.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 02.03.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

extension UILabel {
  
  func sizeLabelToRect(rect: CGRect) {
    self.frame = rect
    var fontSize: CGFloat = 300
    let minFontSize: CGFloat = 5
    
    let constraintSize = CGSizeMake(self.frame.size.width, CGFloat(MAXFLOAT))
    repeat {
      self.font = self.font.fontWithSize(fontSize)
      let textRect: CGRect = self.text!.boundingRectWithSize(constraintSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:self.font], context: nil)
      let labelSize = textRect.size
      if labelSize.height <= self.frame.size.height {
        break
      }
      fontSize -= 2
    } while fontSize > minFontSize
  }
 
  func setTextAndSizeToFit(title: String?) {
    text = title
    sizeToFit()
  }
  
  func setBottomBorder(borderColor: UIColor)
  {
    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)
  }
  
}
