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

import Foundation
import UIKit

class ButtonWithTopAndBottomBorders : UIButton {
  var isClickable = true
  var clickHandler: ((ButtonWithTopAndBottomBorders) -> Void)?
  override func awakeFromNib() {
    super.awakeFromNib()
    backgroundColor = UIColor.whiteColor()
    contentVerticalAlignment = .Center
    titleLabel!.baselineAdjustment = UIBaselineAdjustment.AlignCenters
    titleLabel!.adjustsFontSizeToFitWidth = true
    titleLabel!.lineBreakMode = .ByClipping
    titleLabel!.minimumScaleFactor = 0.01
    titleLabel!.textAlignment = .Center
  }
  
  override func drawRect(rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()
    CGContextSetFillColorWithColor(context!, Color.GreyTextFieldBorderColor)
    CGContextFillRect(context!, CGRect(x: 0, y: 0, width: self.frame.size.width, height: 1))
  }
  
  func addBorderWithColorAndWidth(color: UIColor, borderWidth: CGFloat) {
    let topLine = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 2))
    topLine.backgroundColor = Color.GreyBackButtonColor
    self.addSubview(topLine)
  }
  
  private func changeButton(enabled: Bool) {
    backgroundColor = enabled ? Color.ActionSheetItemHighlightedColor : UIColor.whiteColor()
  }
  
  override func touchesCancelled(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if isClickable {
      changeButton(false)
      print("touchesCancelled")
    }
  }
  
  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if isClickable {
      changeButton(true)
    }
  }
  
  override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if isClickable {
      changeButton(false)
      if !isOutside(touches) {
        clickHandler?(self)
      }
      print("touchesEnded")
    }
  }
  
  private func isOutside(touches: Set<UITouch>) -> Bool {
    let location = touches[touches.startIndex.advancedBy(touches.count - 1)].locationInView(self)
    return ((location.x < 0 || location.x > self.bounds.width) ||
      (location.y < 0 || location.y > self.bounds.height))
  }
  
  override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesMoved(touches, withEvent: event)
    if isClickable {
      changeButton(!isOutside(touches))
    }
  }
  
}
