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

import Foundation
import UIKit

enum MyActionSheetStyle {
  case Square
  case Rounded
}

class MyServicesActionSheetContent : ScrolledViewController, StoryboardFetchable {
  @IBOutlet weak var contentViewHeight: NSLayoutConstraint!
  static var storyboardId: String = "myServicesActionSheet"
  static var currentStyle: MyActionSheetStyle?
  var matchedLabel: UILabel?
  var lastButtonBottomConstraint: NSLayoutConstraint?
  var buttons:[UIButton] = []
  var buttonHandlers:[((button: UIButton) -> Void)?] = []
  var lastButtonIndex = 0
  var firstButtonTopSpace: NSLayoutConstraint?
  static let itemFont:UIFont! = UIFont.boldSystemFontOfSize(17)
  static let itemTitleColor: UIColor = Color.AuthBlueNormalColor
  
  func button_touchUpInside(button: UIButton) {
    buttonHandlers[button.tag]?(button: button)
  }
  
  func generateButton(title: String) -> ButtonWithTopAndBottomBorders {
    let button = ButtonWithTopAndBottomBorders(frame: CGRect(x: 0, y: 0, width: 200, height: 5))
    button.contentEdgeInsets = UIEdgeInsets(top: MyServicesActionSheetContent.currentStyle == MyActionSheetStyle.Rounded ? 15 : 15, left: 10, bottom: MyServicesActionSheetContent.currentStyle == MyActionSheetStyle.Rounded ? 15 : 15, right: 10)
    button.setTitle(title, forState: UIControlState.Normal)
    button.setTitleColor(MyServicesActionSheetContent.itemTitleColor, forState: UIControlState.Normal)
    button.titleLabel?.font = MyServicesActionSheetContent.itemFont
    button.sizeToFit()
    button.frame = CGRect(x: 0, y: 0, width: button.frame.width, height: button.frame.height)
    return button
  }
  
  func returnIfMatch(targetView: UIView, buttonTitle: String) -> UILabel? {
    if !targetView.isKindOfClass(UIButton) {
      if (targetView as? UILabel)?.text == buttonTitle {
        return targetView as? UILabel
      }
    }
    return nil
  }
  
  func findLabelByTitle(subview: UIView, labelTitle: String) {
    for (_, subview) in subview.subviews.enumerate() {
      if let label = returnIfMatch(subview, buttonTitle: labelTitle) {
        matchedLabel = label
      } else {
        findLabelByTitle(subview, labelTitle: labelTitle)
      }
      if matchedLabel != nil {
        break
      }
    }
  }
  
  private static func cornerRadiusByStyle(style: MyActionSheetStyle) -> CGFloat {
    return style == MyActionSheetStyle.Rounded ? 15 : 3
  }
  
  private static func putViewControllerInActionSheet(vc: UIViewController, actionSheet: UIAlertController) {
    vc.view.frame = CGRect(x: 0, y: 0, width: actionSheet.view.frame.width, height: 200)
    vc.view.clipsToBounds = true
    vc.view.layer.cornerRadius = cornerRadiusByStyle(currentStyle!)
    vc.view.superview?.superview?.layer.cornerRadius = cornerRadiusByStyle(currentStyle!)
    vc.view.translatesAutoresizingMaskIntoConstraints = false
    if UIDevice.currentDevice().userInterfaceIdiom == .Pad && actionSheet.view.subviews.count > 0 {
      actionSheet.view.subviews.forEach({$0.removeFromSuperview()})
    }
    let views = ["view" : vc.view]
    actionSheet.view.addSubview(vc.view)
    let viewWidth = UIDevice.currentDevice().userInterfaceIdiom == .Pad ? vc.view.frame.width : vc.view.frame.width - 20
    actionSheet.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view(\(viewWidth))]|", options: [], metrics: nil, views: views))
    if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
      actionSheet.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: [], metrics: nil, views: views))
    } else {
      actionSheet.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]-(\(currentStyle! == .Square ? 58 : 65))-|", options: [], metrics: nil, views: views))
    }
  }
  
  static func fillAndShow(style: MyActionSheetStyle, presentingVC: UIViewController, closure: (actionSheet: MyServicesActionSheetContent) -> Void) {
    currentStyle = style
    let vc = MyServicesActionSheetContent.fromStoryboard()
    let actionSheet = UIAlertController(title: LS("login.action_sheet.title"), message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
    actionSheet.addAction(UIAlertAction(title: LS("cancel"), style: UIAlertActionStyle.Cancel, handler: { action -> Void in
      vc.view.removeFromSuperview()
      vc.removeFromParentViewController()
    }))
    putViewControllerInActionSheet(vc, actionSheet: actionSheet)
    //    actionSheet.popoverPresentationController?.sourceRect = vc.view.bounds
    actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
    actionSheet.popoverPresentationController?.sourceView = vc.view
    presentingVC.presentViewController(actionSheet, animated: true, completion: nil)
    actionSheet.addChildViewController(vc)
    
    closure(actionSheet: vc)
    vc.findLabelByTitle(actionSheet.view, labelTitle: LS("cancel"))
    if let label = vc.matchedLabel {
      let mutableString = NSMutableAttributedString(string: label.text!)
      mutableString.addAttributes([NSForegroundColorAttributeName : MyServicesActionSheetContent.itemTitleColor, NSFontAttributeName: MyServicesActionSheetContent.itemFont], range: NSMakeRange(0, mutableString.length))
      label.attributedText = mutableString
      label.superview?.superview?.layer.cornerRadius = cornerRadiusByStyle(style)
      if style == MyActionSheetStyle.Square {
        label.superview?.translatesAutoresizingMaskIntoConstraints = false
        if vc.buttons.count > 0 {
          label.superview?.superview?.addConstraint(NSLayoutConstraint(item: label.superview!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: vc.buttons[0].frame.height))
        }
        label.reloadInputViews()
      }
    }
    vc.matchedLabel = nil
  }
  
  func addButton(button: ButtonWithTopAndBottomBorders, handler: ((button: UIButton) -> Void)? = nil) {
    button.tag = lastButtonIndex
    contentView.addSubview(button)
    if let handler = handler {
      buttonHandlers.append(handler)
    }
    button.clickHandler = button_touchUpInside
    button.translatesAutoresizingMaskIntoConstraints = false
    contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[button]|", options: [], metrics: nil, views: ["button": button]))
    if lastButtonBottomConstraint != nil {
      contentView.removeConstraint(lastButtonBottomConstraint!)
    }
    if buttons.count == 0 {
      self.firstButtonTopSpace = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
      contentView.addConstraint(firstButtonTopSpace!)
    } else {
      contentView.addConstraint(NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: buttons.last, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
    }
    lastButtonBottomConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
    contentView.addConstraint(lastButtonBottomConstraint!)
    //    contentView.addConstraint(NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: button.frame.height))
    buttons.append(button)
    contentView.resizeToFitSubviews()
    lastButtonIndex += 1
  }
  
  func addTitle(title: String) {
    let button = generateButton(title)
    button.isClickable = false
    button.titleLabel?.font = UIFont.systemFontOfSize(13)
    button.setTitleColor(Color.ActionSheetTitleGrayColor, forState: .Normal)
    contentView.addSubview(button)
    button.translatesAutoresizingMaskIntoConstraints = false
    contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[button]|", options: [], metrics: nil, views: ["button": button]))
    
    if let firstButtonTopSpace = firstButtonTopSpace {
      contentView.removeConstraint(firstButtonTopSpace)
      contentView.addConstraint(NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: buttons[0], attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
    } else {
      lastButtonBottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0)
      contentView.addConstraint(lastButtonBottomConstraint!)
    }
    
    firstButtonTopSpace = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
    contentView.addConstraint(firstButtonTopSpace!)
    
    button.tag = lastButtonIndex
    if buttons.count > 0 {
      buttons.insert(button, atIndex: 0)
      buttonHandlers.insert(nil, atIndex: 0)
      buttons.forEach({$0.tag += 1})
    } else {
      buttons.append(button)
      buttonHandlers.append(nil)
    }
    contentView.resizeToFitSubviews()
    lastButtonIndex += 1
  }
  
}

