//
//  UIViewController.swift


import Foundation
import UIKit
//import ActionSheetPicker
extension UIViewController{
    
    class var identifier: String {
        return String(describing: self)
    }
    func setNavigationTitle(_ title : String, textColor:UIColor? = .black){
        
        self.navigationController?.navigationBar.isHidden = false
        self.navigationItem.title = title
        self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
//        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: Font.HelveticaNeue_Medium(fontSize: 18),NSAttributedString.Key.foregroundColor : textColor ?? .black]
    }
    func setLargeNavigationBar(_ isSet:Bool,textColor:UIColor? = .black, barTintClr:UIColor? = .white){
        self.navigationController?.navigationBar.prefersLargeTitles = isSet
//        self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.font: Font.HelveticaNeue_Medium(fontSize: 18),NSAttributedString.Key.foregroundColor : textColor ?? .black]
    }
    func setBackBarBtnItem(strImageName:String? = "ic_back"){
        
        self.navigationController?.isNavigationBarHidden = false
        let backBtn : UIButton = UIButton(type: .system)
        backBtn.addTarget(self, action: #selector(self.backBarBtnItemTapped(_:)), for: .touchUpInside)
        backBtn.setImage(UIImage(named: strImageName ?? "ic_back"), for: .normal)
        backBtn.setImage(UIImage(named: strImageName ?? "ic_back"), for: .highlighted)
        backBtn.tintColor = UIColor.black
        backBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        backBtn.contentHorizontalAlignment = .left
        let backBarBtnItem = UIBarButtonItem(customView: backBtn)
        self.navigationItem.setLeftBarButton(backBarBtnItem, animated: true)
        
    }
    @IBAction func backBarBtnItemTapped(_ btn : UIButton){
        _ = self.navigationController?.popViewController(animated: true)
    }
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer =     UITapGestureRecognizer(target: self, action:    #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
    
    
    @IBAction func btnDrawerOpenTapped(_ btn : UIButton){
        //self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil)
    }
    @IBAction func dismissItemTapped(_ btn : UIStoryboardSegue){
        self.dismiss(animated: true, completion: nil)
    }
    
    func showAlertView(_ title:String?, _ message: String!, completionHandler: @escaping (_ value: Bool) -> Void){
        
        let alertController = UIAlertController(title: title ?? APP_NAME_WITH_WIDGET, message: message, preferredStyle: .alert)
        let btnOKAction = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
            completionHandler(true)
        }
        alertController.addAction(btnOKAction)
        self.present(alertController, animated: true, completion: nil)
//        alertController.view.tintColor = MIColor.AppThemColor
    }
    
    func showAlertView(_ title:String?, _ message: String!,_ ActionMessage: String!, completionHandler: @escaping () -> Void){
        
        let alertController = UIAlertController(title: title ?? APP_NAME_WITH_WIDGET, message: message, preferredStyle: .alert)
        let btnOKAction = UIAlertAction(title: ActionMessage, style: .default) { (action) -> Void in
            DispatchQueue.main.async {
                completionHandler()
            }
        }
        alertController.addAction(btnOKAction)
        self.present(alertController, animated: true, completion: nil)
//        alertController.view.tintColor = MIColor.AppThemColor
    }
    
    func showAlertViewWithCancelBtn(_ message:String?,_ alertTitle : String?, defaultTitle:String?, cancelTitle:String?, completionHandler: @escaping (_ value: Bool) -> Void) {
        
        let alertController = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)
        let btnOKAction = UIAlertAction(title: defaultTitle, style: .default) { (action) -> Void in
            completionHandler(true)
        }
        let btnCancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { (action) -> Void in
            completionHandler(false)
        }
        
        alertController.addAction(btnCancelAction)
        alertController.addAction(btnOKAction)
        self.present(alertController, animated: true, completion: nil)
//        alertController.view.tintColor = MIColor.AppThemColor
    }
    
    func showActionSheet(cell:UICollectionViewCell? = nil, sender:UIButton? = nil, message : String, preferedStyle : UIAlertController.Style, titleArray : [String],completionHandler : @escaping ( _ value : UIAlertAction) -> Void)
    {
        let alertController = UIAlertController(title: APP_NAME_WITH_WIDGET, message: message, preferredStyle: preferedStyle)
        
        for title in titleArray
        {
            let action = UIAlertAction(title: title, style: .default, handler: { (a) in
                completionHandler(a)
            })
            alertController.addAction(action)
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (a) in
            //completionHandler(a)
            
        })
        alertController.addAction(cancelAction)
        alertController.view.tintColor = UIColor.black
       
        if Utilities.deviceType() == .pad {
            
            
            if #available(iOS 13.0, *) {
                if let popoverPresentationController = alertController.popoverPresentationController {
                    
                    if cell != nil {
                        popoverPresentationController.sourceView = cell
                        popoverPresentationController.sourceRect = CGRect.init(x: cell?.bounds.midX ?? 0, y: cell?.bounds.midY ?? 0, width: 0, height: 0)
                    }else{
                        popoverPresentationController.sourceView = sender
                        popoverPresentationController.sourceRect = CGRect.init(x: sender?.bounds.midX ?? 0, y: sender?.bounds.midY ?? 0, width: 0, height: 0)
                    }
                    popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection(rawValue:0)
                }
                self.present(alertController, animated: true, completion: nil)
            } else {
    
                if cell != nil {
                     alertController.popoverPresentationController?.sourceView = cell
                    alertController.popoverPresentationController?.sourceRect = CGRect.init(x: cell?.bounds.midX ?? 0, y: cell?.bounds.midY ?? 0, width: 0, height: 0)
                }else{
                     alertController.popoverPresentationController?.sourceView = sender
                    alertController.popoverPresentationController?.sourceRect = CGRect.init(x: sender?.bounds.midX ?? 0, y: sender?.bounds.midY ?? 0, width: 0, height: 0)
                }
                alertController.show()
            }
        }else {
             self.present(alertController, animated: true, completion: nil)
        }
    }
    
    //    func showDatePicker(origin: Any, minimumDate: Date?, maximumDate: Date?,displayDate:Date?,datePickerType: UIDatePicker.Mode,interval: Int,displayText:String, completionHandler: @escaping (_ success: Bool, _ picker: ActionSheetDatePicker, _ value: Any?, _ target: Any?) -> Void) {
    ////    var strDisplayText = "Select Date"
    ////    if datePickerType == .time {
    ////      strDisplayText = "Select Hours"
    ////    }
    //
    //    let actionSheetDatePicker: ActionSheetDatePicker = ActionSheetDatePicker(title: displayText, datePickerMode: datePickerType, selectedDate: displayDate, doneBlock: { (picker, value, target) in
    //      completionHandler(true, picker!, value, target)
    //    }, cancel: { (picker) in
    //      completionHandler(false, picker!, nil, nil)
    //    }, origin: origin as? UIView)
    //
    //    if minimumDate != nil {
    //      actionSheetDatePicker.minimumDate = minimumDate
    //    }
    //
    //    if maximumDate != nil {
    //      actionSheetDatePicker.maximumDate = maximumDate
    //    }
    //
    //    if datePickerType == .time {
    //      //actionSheetDatePicker.locale = Locale(identifier: "en_GB") as Locale!
    //      if interval != 0{
    //        actionSheetDatePicker.minuteInterval = interval
    //      }
    //
    //    }
    //    actionSheetDatePicker.show()
    //
    //    /*
    //     actionSheetDatePicker.show(withTitle: "Select Birth Date", datePickerMode: .date, selectedDate: Date(), doneBlock: { (picker, value, target) in
    //     completionHandler(true, picker!, value, target)
    //     }, cancel: { (picker) in
    //     completionHandler(false, picker!, nil, nil)
    //     }, origin: origin as! UIView)
    //     */
    //  }
    
    
    func shareURL(url:URL)  {
        
        let shareItems:Array = [url]
        let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        self.present(activityViewController, animated: true, completion: nil)
        
    }
    
    func showToast(message : String, font: UIFont) {

        let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
        toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        toastLabel.textColor = UIColor.white
        toastLabel.font = font
        toastLabel.textAlignment = .center;
        toastLabel.text = message
        toastLabel.alpha = 1.0
        toastLabel.layer.cornerRadius = 10;
        toastLabel.clipsToBounds  =  true
        self.view.addSubview(toastLabel)
        
//        DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) {
//            toastLabel.removeFromSuperview()
//        }
        
//        UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
//             toastLabel.alpha = 0.0
//        }, completion: {(isCompleted) in
//
//            toastLabel.removeFromSuperview()
//        })
    }
}
public extension UIAlertController {
    func show() {
        let win = UIWindow(frame: UIScreen.main.bounds)
        let vc = UIViewController()
        vc.view.backgroundColor = .clear
        win.rootViewController = vc
        win.windowLevel = UIWindow.Level.alert + 1
        win.makeKeyAndVisible()
        vc.present(self, animated: true, completion: nil)
    }
}
public extension UIView {
    func roundCorners(_ corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
        self.layer.layoutIfNeeded()
        self.layoutIfNeeded()
    }
    func setBorder(clr: UIColor, cornerRadius: CGFloat? = 0.0) {
        self.layer.borderColor = clr.cgColor
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = cornerRadius ?? 0
    }
    func addBottomShadow() {
        layer.masksToBounds = false
        layer.shadowRadius = 4
        layer.shadowOpacity = 1
        layer.shadowColor = UIColor.gray.cgColor
        layer.shadowOffset = CGSize(width: 0 , height: 2)
        layer.shadowPath = UIBezierPath(rect: CGRect(x: 0,
                                                     y: bounds.maxY - layer.shadowRadius,
                                                     width: bounds.width,
                                                     height: layer.shadowRadius)).cgPath
    }
    
    func addShadows(){
        layer.masksToBounds = false
        layer.shadowColor = UIColor.gray.cgColor
        layer.shadowOffset =  CGSize.init(width: -2.0, height: 2.0)//CGSize.zero
        layer.shadowOpacity = 0.5
        layer.shadowRadius = 4

    }
    func addDashedBorders(clr: UIColor? = .gray) {
        let color = clr?.cgColor
        
        let shapeLayer:CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
        
        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color
        shapeLayer.lineWidth = 2
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPattern = [6,3]
        shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath
        
        self.layer.addSublayer(shapeLayer)
    }
    
    
    @IBInspectable
    var cornerRadiuss: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }

       @IBInspectable
       var borderWidths: CGFloat {
            get {
                return layer.borderWidth
            }
           set {
                layer.borderWidth = newValue
           }
         }

        @IBInspectable
        var borderColors: UIColor? {
            get {
                return UIColor(cgColor: layer.borderColor!)
            }
            set {
                layer.borderColor = newValue?.cgColor
            }
        }

        @IBInspectable
       var shadowRadiuss: CGFloat {
            get {
                return layer.shadowRadius
            }
            set {
                layer.shadowColor = #colorLiteral(red: 0.6666666865, green: 0.6666666865, blue: 0.6666666865, alpha: 1).cgColor
                layer.shadowOffset = CGSize(width: 0, height: 2)
                layer.shadowOpacity = 0.5
                layer.masksToBounds = false
               layer.shadowRadius = newValue
            }
        }
    
}

public extension UIWindow {
    
    var visibleViewController: UIViewController? {
        return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
    }
    
    static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
        } else {
            if let pvc = vc?.presentedViewController {
                return UIWindow.getVisibleViewControllerFrom(pvc)
            } else {
                return vc
            }
        }
    }
    func addDashedBorder(clr: UIColor? = .gray) {
        let color = clr?.cgColor
        
        let shapeLayer:CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
        
        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color
        shapeLayer.lineWidth = 2
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPattern = [6,3]
        shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath
        
        self.layer.addSublayer(shapeLayer)
    }
}

extension UIPageViewController {
    var isPagingEnabled: Bool {
        get {
            var isEnabled: Bool = true
            for view in view.subviews {
                if let subView = view as? UIScrollView {
                    isEnabled = subView.isScrollEnabled
                }
            }
            return isEnabled
        }
        set {
            for view in view.subviews {
                if let subView = view as? UIScrollView {
                    subView.isScrollEnabled = newValue
                }
            }
        }
    }
}
