//
//  StoreDetailViewController.swift
//  NearbyStores
//
//  Created by DT Team on 7/2/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import MXParallaxHeader
import GoogleMaps
import Kingfisher
import Atributika
import ImageSlideshow
import AssistantKit
import SwiftWebVC
import MapKit

class StoreDetailViewController: MyUIViewController, ErrorLayoutDelegate, EmptyLayoutDelegate,GMSMapViewDelegate, StoreLoaderDelegate,UIScrollViewDelegate, UITextViewDelegate  {
    
    //adview
    @IBOutlet weak var adSubContainer: UIView!
    @IBOutlet weak var adConstraintHeight: NSLayoutConstraint!
    @IBOutlet weak var adContainer: UIView!
       
    
    @IBOutlet weak var mapsContainer: UIView!
    @IBOutlet weak var mapsSubContainer: UIView!
    @IBOutlet weak var imageView: UIImageView!
    
    @IBOutlet weak var last_offer: EdgeLabel!
    @IBOutlet weak var distance_label: UILabel!
    @IBOutlet weak var featured: EdgeLabel!
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var storeDetailContainer: UIView! //view store
    @IBOutlet weak var storeDetailSubContainer: UIView! //subview store
    @IBOutlet weak var descriptionTextView: UITextView!
    @IBOutlet weak var imageContainer: UIView!

    @IBOutlet weak var storeAddressSubContainer: UIView!
    @IBOutlet weak var storeAddress: UILabel!
 
    @IBOutlet weak var btnsContainer: UIView!
    
    @IBOutlet weak var chatBtn: UIButton!
    @IBOutlet weak var callBtn: UIButton!
    @IBOutlet weak var shareBtn: UIButton!
    @IBOutlet weak var saveBtn: UIButton!
    @IBOutlet weak var unsaveBtn: UIButton!
    
   
    
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var stackViewRightConstraint: NSLayoutConstraint!
    @IBOutlet weak var stackViewLeftConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var detailLabel: UILabel!
    @IBOutlet weak var categorySubContainer: UIView!
    @IBOutlet weak var category: UILabel!
    @IBOutlet weak var imageCategory: UIImageView!
    

    private var store: Store? = nil
    private let slideShow = ImageSlideshow()
    private var lastContentOffset: CGFloat = 0


    func setupSize()  {
        
        if(Device.isPad){
            if Device.screen == .inches_9_7{
                let width = self.view.frame.width/1.5
                let finalSize = self.view.frame.width-width
                self.stackViewLeftConstraint.constant = finalSize/2
                self.stackViewRightConstraint.constant = finalSize/2
            }else{
                let width = self.view.frame.width/1.3
                let finalSize = self.view.frame.width-width
                self.stackViewLeftConstraint.constant = finalSize/2
                self.stackViewRightConstraint.constant = finalSize/2
            }
        }
        
    }
    
   
    
    @IBAction func onCategoryAction(_ sender: Any) {
        
     
        
    }
    
    
    @IBAction func chatAction(_ sender: Any) {
        
        if let store = self.store {
            
            if Session.isLogged(){
                startMessenger(client_id: store.user_id)
            }else{
                let sb = UIStoryboard(name: "Login", bundle: nil)
                if let vc = sb.instantiateInitialViewController() {
                    self.present(vc, animated: true)
                }
            }
            
        }
    }
    
    
    
    @IBAction func callAction(_ sender: Any) {
        
        if let store = self.store {
            
            Utils.printDebug("Phone: \(store.phone)")
            
            let phone = store.phone.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
            
            let result = phone.isValid(regex: .phone)
            
            if result{
                if let url = URL(string: "tel://\(phone)"), UIApplication.shared.canOpenURL(url) {
                    if #available(iOS 10, *) {
                        UIApplication.shared.open(url)
                    } else {
                        UIApplication.shared.openURL(url)
                    }
                }else{
                    
                    let message: [String:String] = ["alert":"This app is not allowed to query for scheme tel".localized]
                    self.showAlertError(title: "Alert!".localized, content: message, msgBnt: "OK".localized)
                    
                }
            }else{
                
                let message: [String:String] = ["alert":"This app is not allowed to query for scheme tel or Phone number is not valid".localized]
                self.showAlertError(title: "Alert!".localized, content: message, msgBnt: "OK".localized)
                
            }
            
            
        }
        
    }
    
    
    @IBAction func shareAction(_ sender: Any) {
        
        if let id = storeId, let store = Store.findById(id: id) {
            
            _ = store.latitude
            _ = store.longitude
            //_ = "https://maps.google.com/?ll=\(lat),\(lng)"
            
            let text = "%@ - Only on %@ \n %@".localized.format(arguments: store.name,AppConfig.APP_NAME,store.link)
        
            //%@ - Only on %@ \n %@
            
            let textShare = [ text ]
            let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
            activityViewController.popoverPresentationController?.sourceView = self.view
            self.present(activityViewController, animated: true, completion: nil)
            
        }
        
    }
    
    @IBAction func saveAction(_ sender: Any) {
            
    }
    
 
    @IBAction func unsaveAction(_ sender: Any) {
            
    }
    
    
  
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
     
        
        if scrollView.contentOffset.y > -100{
            
            navigationBar.isTranslucent = false
            navigationBarItem.titleView?.isHidden = false
           
            UIView.animate(withDuration: 0.2) {
                self.navigationBar.layoutIfNeeded()
            }
            
            
        }else{
            
            //make it transeparent
            navigationBar.isTranslucent = true
            navigationBarItem.titleView?.isHidden = true

            UIView.animate(withDuration: 0.2) {
                self.navigationBar.layoutIfNeeded()
            }

        }
        
        
        update_icon_template_scrolling()
       
        // update the new position acquired
        self.lastContentOffset = scrollView.contentOffset.y
    }
    
    
    
    
      func update_icon_template_scrolling(){

          if scrollView.contentOffset.y > -100{
            
            //make white
            for bu in navigationBarItem.rightBarButtonItems!{
                bu.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
            }
            
            for bu in navigationBarItem.leftBarButtonItems!{
                bu.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
            }
              
          }else{
            
          
            //make white
            for bu in navigationBarItem.rightBarButtonItems!{
                bu.tintColor = AppDesignUtils.defaultModeColor(dark: Colors.primaryColor, light: .white)
            }
            
            for bu in navigationBarItem.leftBarButtonItems!{
                bu.tintColor = AppDesignUtils.defaultModeColor(dark: Colors.primaryColor, light: .white)
            }
            
          }
          
      }

    
   
  
    
    
    var storeId: Int? = nil

    var viewManager: LoaderViewManager =  LoaderViewManager()
    
    func setupViewloader()  {
        
        //setup view loader, Error, Empty layouts
        viewManager.setup(parent: mainView)
        viewManager.getEmptyLayout().delegate = self
        viewManager.getErrorLayout().delegate = self
        
        if Session.isLogged() ==  false {
            return
        }
    }
    
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        
        return titleLabel
        
    }()
    
    func setupNavBarTitles(title: String) {
        
        
        let rect = CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height)
        topBarTitle.frame = rect
        topBarTitle.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
        topBarTitle.leftTextInset = 5
        
        topBarTitle.text = title
        navigationBarItem.titleView = topBarTitle
        
    }
    
    
    func setupNavBarButtons() {
        
        let color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        
        //arrow back icon
        var arrowImage: UIImage? = nil
        if Utils.isRTL(){
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: color)
        }else{
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: color)
        }
        

        let customBarButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
        customBarButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: color)
        

        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
        
    }
    
    @objc func onBackHandler()  {
        self.dismiss(animated: true)
    }
    
    
    
    func onRate(rating: Double, review: String) {
        //add review
        
        let message: [String: String] = ["alert": "Thank for your review!".localized]
        self.showAlertError(title: "Alert",content: message,msgBnt: "OK")
      
    }
    
   
    
    var mapView: GMSMapView? = nil
    
    
    func setupGoogleMaps(lat:Double,lng:Double) {
        
        let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 14.0)
        
        let width = self.mapsSubContainer.frame.width
        self.mapView = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: width, height: self.mapsSubContainer.frame.height), camera: camera)


        mapView?.delegate = self
        mapView?.settings.setAllGesturesEnabled(false)
        
        if let mapView = self.mapView  {
            
            
            self.mapsSubContainer.addSubview(mapView)
            
            
            Utils.printDebug("mapView \(mapView.frame)")
            Utils.printDebug("mapsContainer \(mapsSubContainer.frame)")
            
            mapView.backgroundColor = UIColor.yellow
            
            mapView.animate(toZoom: 14)
            // Creates a marker in the center of the map.
            let marker = GMSMarker()
            marker.position = CLLocationCoordinate2D(latitude:  lat, longitude: lng)
            marker.map = mapView
            
            
            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 15)
            self.mapView?.camera = camera
            self.mapView?.animate(to: camera)
            
            
            self.mapView?.isHidden = true
            
            DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                
                
                let frame = self.mapsContainer.bounds
                self.mapView?.frame = frame
                self.mapView?.bounds = self.mapsContainer.bounds
                self.view.layoutIfNeeded()
                
                
                self.mapView?.isHidden = false
                
                Utils.printDebug("bounds: \(self.mapsContainer.bounds)")

            }
            
           
           
            
        }
        
    }
    
  
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupSize()
        
         StoreDetailViewController.mInstance = self
        
        self.navigationBar.isTranslucent = false
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.tintColor = .white
        
        
        self.setupNavBarTitles(title: "Store detail".localized)
        self.setupNavBarButtons()
        self.setupViewloader()
        self.setupViews()
        
        

        if let id = storeId, let _ = Store.findById(id: id){
            self.setupStoreDetail()
        }else{
            load()
        }
        
      
        
        
    }
  
    
    override func viewWillDisappear(_ animated: Bool) {
       
    }
    
    func setupViews() {
        
        self.scrollView.delegate = self
        
        self.view.backgroundColor = Colors.highlightedGray
        
        self.stackView.distribution = .fillProportionally
        
        scrollView.parallaxHeader.view = self.imageContainer
        scrollView.parallaxHeader.height = self.imageView.frame.height;
        scrollView.parallaxHeader.mode = .fill;
        scrollView.parallaxHeader.minimumHeight = 0;
        

        //distance tag
        distance_label.initDefaultFont(size: 12)

        
        featured.leftTextInset = 15
        featured.rightTextInset = 15
        featured.bottomTextInset = 10
        featured.topTextInset = 10
        featured.backgroundColor = Colors.featuredTagColor
        featured.isHidden = true
        featured.initItalicFont()
        
        
        //offers tag
        last_offer.leftTextInset = 15
        last_offer.rightTextInset = 15
        last_offer.topTextInset = 10
        last_offer.bottomTextInset = 10
        last_offer.backgroundColor = Colors.primaryColor
        last_offer.initDefaultFont()
        last_offer.isHidden = true
        
        
        self.storeDetailSubContainer.layer.cornerRadius = 5/UIScreen.main.nativeScale
        self.storeDetailSubContainer.layer.masksToBounds = true
        
        
        
        self.storeAddressSubContainer.layer.cornerRadius = 5/UIScreen.main.nativeScale
        self.storeAddressSubContainer.layer.masksToBounds = true
        
       
        self.btnsContainer.layer.cornerRadius = 5/UIScreen.main.nativeScale
        self.btnsContainer.layer.masksToBounds = true
    
        self.categorySubContainer.layer.cornerRadius = 5/UIScreen.main.nativeScale
        self.categorySubContainer.layer.masksToBounds = true
        
        
        self.chatBtn.setIcon(icon: .ionicons(.chatbubbles), iconSize: 24, color: Colors.primaryColor, forState: .normal)
        self.callBtn.setIcon(icon: .ionicons(.androidCall), iconSize: 24, color: Colors.primaryColor, forState: .normal)
        self.shareBtn.setIcon(icon: .ionicons(.androidShareAlt), iconSize: 24, color: Colors.primaryColor, forState: .normal)
        self.saveBtn.setIcon(icon: .ionicons(.heart), iconSize: 24, color: Colors.primaryColor, forState: .normal)
        self.unsaveBtn.setIcon(icon: .openIconic(.heart), iconSize: 24, color: .white, forState: .normal)
        
    
        self.chatBtn.setCustomButtonControlStyle()
        self.callBtn.setCustomButtonControlStyle()
        self.shareBtn.setCustomButtonControlStyle()
        self.saveBtn.setCustomButtonControlStyle()
        self.unsaveBtn.setCustomButtonControlStyle(active: true)
    
        
        self.slideShow.translatesAutoresizingMaskIntoConstraints = false

        var constraints = [NSLayoutConstraint]()

        constraints.append(NSLayoutConstraint(
            item: self.slideShow,
            attribute: NSLayoutConstraint.Attribute.right,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: self.imageView,
            attribute: NSLayoutConstraint.Attribute.right,
            multiplier: 1, constant: 0)
        )

        constraints.append(NSLayoutConstraint(
            item: self.slideShow,
            attribute: NSLayoutConstraint.Attribute.top,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: self.imageView,
            attribute: NSLayoutConstraint.Attribute.top,
            multiplier: 1, constant: 0)
        )

        constraints.append(NSLayoutConstraint(
            item: self.slideShow,
            attribute: NSLayoutConstraint.Attribute.bottom,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: self.imageView,
            attribute: NSLayoutConstraint.Attribute.bottom,
            multiplier: 1, constant: 0)
        )

        constraints.append(NSLayoutConstraint(
            item: self.slideShow,
            attribute: NSLayoutConstraint.Attribute.left,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: self.imageView,
            attribute: NSLayoutConstraint.Attribute.left,
            multiplier: 1, constant: 0)
        )
        
       
        self.imageView.addSubview(slideShow)
        self.imageView.addConstraints(constraints)
        
        self.slideShow.pageIndicator = nil
        self.slideShow.contentScaleMode = .scaleAspectFill
        
        let gestureRecognizerImageView = UITapGestureRecognizer(target: self, action: #selector(didTapOnImage))
        self.imageContainer.addGestureRecognizer(gestureRecognizerImageView)
        
        let gestureRecognizerGeoMap = UITapGestureRecognizer(target: self, action: #selector(didTapOnGeoMaps))
        self.mapsContainer.addGestureRecognizer(gestureRecognizerGeoMap)
        
        
        //localization
        self.featured.text = "Featured".localized
      
     
        self.featured.initBolodFont()
        self.featured.text = "Featured".localized.uppercased()
        
        
        self.category.textColor = .white
        self.category.initBolodFont()
        self.storeAddress.initDefaultFont()
        self.detailLabel.initBolodFont()
        self.detailLabel.numberOfLines = 0
        
    }
    
    @objc func didTapOnImage() {
        if #available(iOS 13.0, *){
            self.slideShow.presentFullScreenControllerForIos13(from: self)
        }else{
            self.slideShow.presentFullScreenController(from: self)
        }
    }
    
    @objc func didTapOnGeoMaps() {
        
        if let id = storeId, let store = Store.findById(id: id){
            
            let latitude: CLLocationDegrees = store.latitude
            let longitude: CLLocationDegrees = store.longitude
                                                  
            let regionDistance:CLLocationDistance = store.distance
            let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
                                                  
            let regionSpan = MKCoordinateRegion.init(center: coordinates, latitudinalMeters: regionDistance, longitudinalMeters: regionDistance)
            let options = [
                MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
                MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
            ]
                                
            let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
            let mapItem = MKMapItem(placemark: placemark)
            mapItem.name = store.name
            mapItem.openInMaps(launchOptions: options)
            
        }
        
    }
    
   
    
    
  
    func setupStoreDetail()  {
        
        if let id = storeId, let store = Store.findById(id: id){
            
        
            self.detailLabel.text = store.name
            
            if let session = Session.getInstance(), let user = session.user{
                if user.id == store.user_id{
                    self.chatBtn.isHidden = true
                }
            }
            
            
            self.store = store
            
          

            if store.featured == 1 {
                //self.featured.isHidden = false
            }else{
               // self.featured.isHidden = true
            }
            
            
            let distance = store.distance.calculeDistance()
            self.distance_label.text = distance.getCurrent(type: Distance.Types.Kilometers)
            
        
            
            
            
            //setup maps
            self.setupGoogleMaps(lat: store.latitude, lng: store.longitude)
            
            //setup imageview
            var imagesInputs:[InputSource] = []
            if store.listImages.count > 0 {
                
                
                for index in 0...store.listImages.count-1{
                    let url = store.listImages[index].url500_500
                    if let k = KingfisherSource(urlString: url){
                         imagesInputs.append(k)
                    }
                }
                
                self.slideShow.setImageInputs(imagesInputs)
                
                
                if let first = store.listImages.first {
                    
                    let url = URL(string: first.url500_500)
                    self.imageView.kf.indicatorType = .activity
                    self.imageView.kf.setImage(with: url,options: [.transition(.fade(0.2))])
                    
                }
                
            }
            
            
            if imagesInputs.count == 0 {
                if let img = UIImage(named: "default_store_image") {
                    self.imageView.image = img
                }
            }
            
            
            //setup store description and resize height of textview
         
            
            if store.detail != ""{
                
                Utils.printDebug("\(store.detail)")
                
                Utils.printDebug("Height-before: \(self.storeDetailSubContainer.frame.height)")
                //description Text View
                
                self.descriptionTextView.delegate = self
                self.descriptionTextView.isUserInteractionEnabled = true // default: true
                self.descriptionTextView.isEditable = false // default: true
                self.descriptionTextView.isSelectable = true // default: true
                self.descriptionTextView.dataDetectorTypes = [.link]
                self.descriptionTextView.isScrollEnabled = false
                
                self.descriptionTextView.textAlignment = .natural
                self.descriptionTextView.tintColor = Colors.primaryColor
                
                
                let attributedString  = store.detail.toHtml().attributedString
                self.descriptionTextView.attributedText = attributedString;
                
                
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    
                    Utils.printDebug("Height-after: \(self.storeDetailSubContainer.frame.height)")
                  
                    //ceate a constraint to fix height size
                    self.storeDetailSubContainer.translatesAutoresizingMaskIntoConstraints = false
                  
                    let heightConstraint = NSLayoutConstraint(item: self.storeDetailSubContainer, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: self.storeDetailSubContainer.frame.height)
                    
                    self.storeDetailContainer.addConstraints([heightConstraint])
                    self.storeDetailContainer.layoutIfNeeded()
                    self.storeDetailSubContainer.layoutIfNeeded()
                  
                 
                }
                
               
                
            }
          
            
            let icon = UIImage.init(icon: .googleMaterialDesign(.place), size: CGSize(width: 24, height: 24), textColor: Colors.primaryColor)
            
    
            self.storeAddress.text = store.address
            
            if Utils.isRTL(){
                self.storeAddress.setRightIcon(image: icon)
            }else{
                self.storeAddress.setLeftIcon(image: icon)
            }
            
            self.storeAddress.textColor = UIColor.gray
         
            //store title
            self.setupNavBarTitles(title: store.name)
            
    
            
            if store.canChat == 0{
                self.chatBtn.isHidden = true
            }
            
           
  
        }else{
            //sync with server
            load()
        }
        
    }

    
    func onReloadAction(action: EmptyLayout) {
        self.load()
    }
    
    func onReloadAction(action: ErrorLayout) {
        self.load()
    }
    
    
    //load store
    var storeLoader: StoreLoader = StoreLoader()
    
    func load () {
        
        viewManager.showAsLoading()
    
        self.storeLoader.delegate = self
        
        //Get current Location
        
        var parameters = [
            "limit"          : "1"
        ]
        
        if let guest = Guest.getInstance() {
            
            parameters["latitude"] = String(guest.lat)
            parameters["longitude"] = String(guest.lng)
            
          
            if let store_id = self.storeId{
                parameters["store_id"] = String(store_id)
            }
           
        }
        
        Utils.printDebug("\(parameters)")
        
        self.storeLoader.load(url: Constances.Api.API_USER_GET_STORES,parameters: parameters)
  
    }
    
    func success(parser: StoreParser,response: String) {
        
        self.viewManager.showResult()
       
        if parser.success == 1 {

            let stores = parser.parse()
           
            if stores.count > 0 {
                
                stores[0].save()
                self.setupStoreDetail()
                
            }else{
                viewManager.showAsEmpty()
            }
            
        }else {
            
            if parser.errors != nil {
                viewManager.showAsError()
            }
            
        }
        
    }
    
   
    
    func error(error: Error?,response: String) {
        
        self.viewManager.showAsError()
        
        Utils.printDebug("===> Request Error! ListStores")
        Utils.printDebug("\(response)")
        
    }
    
    func calculateEstimatedFrame(content: String,fontSize: Float) -> CGSize {
        
        let size = CGSize(width: 250, height: 1000)
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimatedFrame = NSString(string: content).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: CGFloat(fontSize))], context: nil)
        
    
        let width = estimatedFrame.width
        let height = estimatedFrame.height
       
        return CGSize(width: width, height: height)
    }
    
    static var mInstance: StoreDetailViewController? = nil
    
    
    func startGalleryLsit(store_id: Int)  {
        
       
    }
  
    func startMessenger(client_id: Int) {
        
        let sb = UIStoryboard(name: "Messenger", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: MessengerViewController = sb.instantiateViewController(withIdentifier: "messengerVC") as! MessengerViewController
            ms.client_id = client_id
            present(ms, animated: true)
        }
        
    }
    
  
    
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        
        let webVC = SwiftModalWebVC(pageURL: URL, theme: .dark, dismissButtonStyle: .cross, sharingEnabled: true)
        //self.navigationController?.pushViewController(webVC, animated: true)
        self.present(webVC, animated: true, completion: nil)
        
        return false
    }

   

}


extension ImageSlideshow {
    @discardableResult
    open func presentFullScreenControllerForIos13(from controller: UIViewController) -> FullScreenSlideshowViewController {
        let fullscreen = FullScreenSlideshowViewController()
        fullscreen.pageSelected = {[weak self] (page: Int) in
            self?.setCurrentPage(page, animated: false)
        }

        fullscreen.initialPage = currentPage
        fullscreen.inputs = images
       fullscreen.transitioningDelegate = slideshowTransitioningDelegate
        fullscreen.modalPresentationStyle = .fullScreen
        controller.present(fullscreen, animated: true, completion: nil)

        return fullscreen
    }
}

