//
//  UIViewController+AddBackButton.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 04.02.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

extension UIViewController {
    
    func addButton(selectorName: String, textColor: UIColor? = nil) {
        let customView = UIView(frame: CGRect(x: 0, y: 0, width: 65, height: 41))
        let imageView = UIImageView(image: UIImage(named: "navbar_back_icon_normal"))
        imageView.image = imageView.image!.imageWithRenderingMode(.AlwaysTemplate)
        customView.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        let label = UILabel(frame: CGRect.zero)
        label.text = LocalizedString("back")
        label.textColor = textColor
        customView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        let views = ["imageView" : imageView, "label" : label]
        customView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-7-[imageView(27)]-7-|", options: [], metrics: nil, views: views))
        customView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-7-[label]-7-|", options: [], metrics: nil, views: views))
        customView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(-10)-[imageView(25)]-(-2)-[label]|", options: [], metrics: nil, views: views))
        let quitTapRecognizer = UITapGestureRecognizer(target:self, action:Selector(selectorName))
        customView.addGestureRecognizer(quitTapRecognizer)
        customView.userInteractionEnabled = true
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: customView)
        navigationController?.navigationBar.tintColor = Color.GreyBackButtonColor
    }
    
    func addBackButtonForModal(textColor: UIColor? = nil) {
        addButton("backFromModal", textColor: textColor)
    }
    
    func addBackButtonForDefault(textColor: UIColor? = nil) {
        addButton("back", textColor: textColor)
    }
    
    func backFromModal() {
        PKNotification.loading(false)
        self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func back() {
        PKNotification.loading(false)
        self.navigationController!.popViewControllerAnimated(true)
    }
}
