//
//   Extensions.swift
//  SupplycoMobile
//
//  Created by macbook pro on 14/08/20.
//  Copyright © 2020 macbook pro. All rights reserved.
//

import Foundation
import  UIKit

extension UIViewController {
    func displayAlert(message:String)
    {
        let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }
}
extension  UITextField {
    func addBottomBorder(){
        let bottomLine = CALayer()
        bottomLine.frame = CGRect(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
        bottomLine.backgroundColor = UIColor.gray.cgColor
        borderStyle = .none
        layer.addSublayer(bottomLine)
    }
}
extension UILabel
{
    
        func underline() {
            if let textString = self.text {
                let attributedString = NSMutableAttributedString(string: textString)
                attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
                                              value: NSUnderlineStyle.single.rawValue,
                                              range: NSRange(location: 0, length: textString.count))
                self.attributedText = attributedString
            }
        }
    
    
    func bottomBorder(){
        
        let bottomLayer = CALayer()
        bottomLayer.frame = CGRect(x: 0, y: frame.height - 1, width: frame.width - 2, height: 1)
        bottomLayer.backgroundColor = UIColor.lightGray.cgColor
        layer.addSublayer(bottomLayer)
    }
    
        
        func strikeThrough(_ isStrikeThrough:Bool) {
            if isStrikeThrough {
                if let lblText = self.text {
                    let attributeString =  NSMutableAttributedString(string: lblText)
                    attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0,attributeString.length))
                    self.attributedText = attributeString
                }
            } else {
                if let attributedStringText = self.attributedText {
                    let txt = attributedStringText.string
                    self.attributedText = nil
                    self.text = txt
                    return
                }
            }
        }
    
    func createDashedLineForLbl( ) {
        let shapeLayer = CAShapeLayer()
        
        shapeLayer.strokeColor = UIColor.orange.cgColor
        shapeLayer.lineWidth = 2
        shapeLayer.lineDashPattern = [2, 2]
        
        
        layer.addSublayer(shapeLayer)
    }
    
}
extension UIView {
    
    
    func addDashedBorder(_ x : CGFloat , width : CGFloat , color : UIColor)
      {
        self.backgroundColor = .clear
        let color = color.cgColor
        let shapeLayer:CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: 0, width: width, height: frameSize.height)
        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: 0, y: frameSize.height/2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color
        shapeLayer.lineWidth = 1
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPattern = [4,4]
        shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath
        self.layer.addSublayer(shapeLayer)
        }
    
    // OUTPUT 1
    func dropShadow(scale: Bool = true) {
        layer.masksToBounds = false
        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize(width: -5, height: 5)
        layer.shadowRadius = 5
        
        /* layer.shadowPath = UIBezierPath(rect: bounds).cgPath
         layer.shouldRasterize = true
         layer.rasterizationScale = scale ? UIScreen.main.scale : 1 */
    }
    
    // OUTPUT 2
    func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
        layer.masksToBounds = false
        layer.shadowColor = color.cgColor
        layer.shadowOpacity = opacity
        layer.shadowOffset = offSet
        layer.shadowRadius = radius
        
//        layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
//        layer.shouldRasterize = true
//        layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }
    
    func createDashedLine(color:UIColor ) {
        let shapeLayer = CAShapeLayer()
        
        shapeLayer.strokeColor = color.cgColor
        shapeLayer.lineWidth = 2
        shapeLayer.lineDashPattern = [4, 4]
        
        let path = CGMutablePath()
        path.addLines(between: [CGPoint(x: 0, y: 0),
                                       CGPoint(x: self.frame.width, y: 0)])
        shapeLayer.path = path
        
        layer.addSublayer(shapeLayer)
    }
    
    func roundCorners(corners: UIRectCorner, radius: CGFloat) {
            let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            layer.mask = mask
        }
}
extension UITextField {
    
    func addShadowToTextField(color: UIColor , cornerRadius: CGFloat) {
        
        self.backgroundColor = UIColor.white
        self.layer.masksToBounds = false
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOffset = CGSize(width: 0, height: 0)
        self.layer.shadowOpacity = 1.0
        self.backgroundColor = .white
        self.layer.cornerRadius = cornerRadius
    }
}
extension UIImageView {
    func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else {
                    self.loadDefaultImage()
                    return }
            DispatchQueue.main.async() { [weak self] in
                self?.image = image
            }
            }.resume()
    }
    func loadDefaultImage() {
        
        DispatchQueue.main.async() { [weak self] in
            
            self?.image = UIImage(named: "placeholder")
        }
    }
    func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode)
    }
}

extension UITextField {
    
    func addroundborder()
    {
        self.layer.cornerRadius = 8.0
        self.layer.borderColor = UIColor.gray.cgColor
        self.layer.borderWidth = 0.1
    }
    
    
}
extension UITextField {
    func setLeftPaddingPoints(_ amount:CGFloat){
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
        self.leftView = paddingView
        self.leftViewMode = .always
    }
    func setRightPaddingPoints(_ amount:CGFloat) {
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
        self.rightView = paddingView
        self.rightViewMode = .always
    }
}


extension UIView {
    
    func addTopAndBottomBorders() {
        let thickness: CGFloat = 0.5
        let topBorder = CALayer()
        let bottomBorder = CALayer()
        topBorder.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: thickness)
        topBorder.backgroundColor = UIColor.darkGray.cgColor
        bottomBorder.frame = CGRect(x:0, y: self.frame.size.height - thickness, width: self.frame.size.width, height:thickness)
        bottomBorder.backgroundColor = UIColor.darkGray.cgColor
        self.layer.addSublayer(topBorder)
        self.layer.addSublayer(bottomBorder)
    }
    func addTopBorder(){
        let thickness: CGFloat = 0.5
        let topBorder = CALayer()
        topBorder.frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: thickness)
        topBorder.backgroundColor = UIColor.darkGray.cgColor
        self.layer.addSublayer(topBorder)
    }
    func addBottomBorderView(){
        let thickness: CGFloat = 0.5
         let bottomBorder = CALayer()
        bottomBorder.frame = CGRect(x:0, y: self.frame.size.height - thickness, width: self.frame.size.width, height:thickness)
        bottomBorder.backgroundColor = UIColor.darkGray.cgColor
        self.layer.addSublayer(bottomBorder)
    }
}

extension Double {
    var twoDecimalString:String {
        return String(format: "%.2f", self)
    }
}


extension UIView
{
    
    func setupUIViewFrame(radius: CGFloat)
    {
        self.layer.cornerRadius =  radius
        self.layer.masksToBounds = false
        self.layer.shadowRadius = 3.0
        self.layer.shadowColor = UIColor.lightGray.cgColor
        self.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
        self.layer.shadowOpacity = 1.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
    }

}
extension Date {
    func string(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

extension UIButton
{
    func setupNormalButtonFrame(bordercolor: UIColor)
    {
        self.layer.cornerRadius = 5
        self.layer.borderColor = bordercolor.cgColor
        self.layer.borderWidth = 1
        self.setTitleColor(UIColor(red: 181/255, green: 181/255, blue: 181/255, alpha: 1), for: .normal)
        self.layer.backgroundColor = UIColor.white.cgColor
        
    }
}

extension UIViewController {
//    func showSnackBar(Message : String,snackbar : MJSnackBar)
//    {
//        let data = MJSnackBarData(withIdentifier: 1, message: Message, andActionMessage: "", objectSaved: nil)
//        DispatchQueue.main.async {
//            snackbar.backgroundColor = UIColor.themeYellowColor
//            //snackbar.actionColorColor = UIColor.black
//            snackbar.messageFont = UIFont.systemFont(ofSize: 14)
//            snackbar.messageColor = UIColor.black
//            snackbar.show(data: data, onView: self.view)
//        }
//    }
    
   
    
//    
    
    
    func hideKeyboardWhenTappedAround() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
    
    
    
    func addKeyboardObserver() {
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardNotifications(notification:)),
                                                   name: UIResponder.keyboardWillChangeFrameNotification,
                                                   object: nil)
        }
        
        func removeKeyboardObserver(){
            NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        }
        
        // This method will notify when keyboard appears/ dissapears
        @objc func keyboardNotifications(notification: NSNotification) {
            
            var txtFieldY : CGFloat = 0.0  //Using this we will calculate the selected textFields Y Position
            let spaceBetweenTxtFieldAndKeyboard : CGFloat = 5.0 //Specify the space between textfield and keyboard
            
            
            var frame = CGRect(x: 0, y: 0, width: 0, height: 0)
            if let activeTextField = UIResponder.currentFirst() as? UITextField ?? UIResponder.currentFirst() as? UITextView {
                // Here we will get accurate frame of textField which is selected if there are multiple textfields
                frame = self.view.convert(activeTextField.frame, from:activeTextField.superview)
                txtFieldY = frame.origin.y + frame.size.height
            }
            
            if let userInfo = notification.userInfo {
                // here we will get frame of keyBoard (i.e. x, y, width, height)
                let keyBoardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
                let keyBoardFrameY = keyBoardFrame!.origin.y
                let keyBoardFrameHeight = keyBoardFrame!.size.height
                
                var viewOriginY: CGFloat = 0.0
                //Check keyboards Y position and according to that move view up and down
                if keyBoardFrameY >= UIScreen.main.bounds.size.height {
                    viewOriginY = 0.0
                } else {
                    // if textfields y is greater than keyboards y then only move View to up
                    if txtFieldY >= keyBoardFrameY {
                        
                        viewOriginY = (txtFieldY - keyBoardFrameY) + spaceBetweenTxtFieldAndKeyboard
                        
                        //This condition is just to check viewOriginY should not be greator than keyboard height
                        // if its more than keyboard height then there will be black space on the top of keyboard.
                        if viewOriginY > keyBoardFrameHeight { viewOriginY = keyBoardFrameHeight }
                    }
                }
                
                //set the Y position of view
                self.view.frame.origin.y = -viewOriginY
            }
        }
    
   
}
extension UIResponder {
    
    static weak var responder: UIResponder?
    
    static func currentFirst() -> UIResponder? {
        responder = nil
        UIApplication.shared.sendAction(#selector(trap), to: nil, from: nil, for: nil)
        return responder
    }
    
    @objc private func trap() {
        UIResponder.responder = self
    }
}

extension UINavigationController
{

    func backToViewController(viewController: Swift.AnyClass) {

            for element in viewControllers as Array {
                if element.isKind(of: viewController) {
                    self.popToViewController(element, animated: true)
                break
            }
        }
    }
}


class InsetLabel: UILabel {
    
    override func drawText(in rect: CGRect) {
        
            super.drawText(in: rect.inset(by: UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)))
            
     
    }
}

extension FloatingPoint {
    var whole: Self { modf(self).0 }
    var fraction: Self { modf(self).1 }
}
// remove array element duplication
extension Array where Element:Equatable {
    func removeDuplicates() -> [Element] {
        var result = [Element]()

        for value in self {
            if result.contains(value) == false {
                result.append(value)
            }
        }

        return result
    }
}

extension UINavigationController {
  func popToViewController(ofClass: AnyClass, animated: Bool = true) {
    if let vc = viewControllers.last(where: { $0.isKind(of: ofClass) }) {
      popToViewController(vc, animated: animated)
    }
  }
}

enum AddressType
{
    case Home
    case Work
    case other
}


extension CALayer {
    
    func leftAnimation(duration:CFTimeInterval) {
        let animation = CATransition()
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        animation.duration = duration
        animation.type = CATransitionType.push
        animation.subtype = CATransitionSubtype.fromRight
        self.add(animation, forKey: CATransitionType.push.rawValue)
    }
    
    func rightAnimation(duration:CFTimeInterval) {
        let animation = CATransition()
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        animation.duration = duration
        animation.type = CATransitionType.push
        animation.subtype = CATransitionSubtype.fromLeft
        self.add(animation, forKey: CATransitionType.push.rawValue)
    }
}
