//
//  StoreDetailViewController.swift
//  NearbyStores
//
//  Created by Amine 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, RateDialogViewControllerDelegate, StoreLoaderDelegate,UIScrollViewDelegate, UITextViewDelegate, OptionsDelegate  {
    
    //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_product: 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 btnsContainerStackView: UIStackView!
    @IBOutlet weak var chatBtn: UIButton!
    @IBOutlet weak var callBtn: UIButton!
    @IBOutlet weak var websiteBtn: UIButton!
    @IBOutlet weak var socialMediaBtn: 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!
    
    @IBOutlet weak var recent_offers_container: UIView!
    @IBOutlet weak var recent_products_container: UIView!
    
    @IBOutlet weak var recent_offers_cv: UIView!
    @IBOutlet weak var recent_product_cv: UIView!
    
    @IBOutlet weak var opening_time_sub_container: UIView!
    @IBOutlet weak var opening_time_container: UIStackView!
    @IBOutlet weak var opening_time_label: UILabel!
    @IBOutlet weak var opening_time_text_view: UITextView!
    @IBOutlet weak var open_store_badge: EdgeLabel!
    
    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) {
        
        if let id = self.storeId, let store = Store.findById(id: id){
            
            let sb = UIStoryboard(name: "StoresList", bundle: nil)
            if sb.instantiateInitialViewController() != nil {
                
                let ms: StoresLsitViewController = sb.instantiateViewController(withIdentifier: "storeslistVC") as! StoresLsitViewController
                
                ms.request = ListStoresView.Request.nearby
                ms.category_id = store.category_id
                
                self.present(ms, animated: true)
                
            }
        }
        
    }
    
    
    @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 websiteAction(_ sender: Any) {
        
        if let id = storeId, let store = Store.findById(id: id) {
            
            if let url = URL(string: store.website), UIApplication.shared.canOpenURL(url) {
                let webVC = SwiftModalWebVC(pageURL: url, theme: .dark, dismissButtonStyle: .cross, sharingEnabled: true)
                //self.navigationController?.pushViewController(webVC, animated: true)
                self.present(webVC, animated: true, completion: nil)
            }
            
        }
        
    }
    
    
    
    @IBAction func socialMediaAction(_ sender: Any) {
        
        if let id = storeId, let store = Store.findById(id: id) {
            
            if let url = URL(string: store.social_media), UIApplication.shared.canOpenURL(url) {
                
                if(store.social_media.contains("wa.me")){
                    UIApplication.shared.open(url)
                    return
                }
                
                let webVC = SwiftModalWebVC(pageURL: url, theme: .dark, dismissButtonStyle: .cross, sharingEnabled: true)
                self.present(webVC, animated: true, completion: nil)
            }
            
        }
        
    }
    
    @IBAction func saveAction(_ sender: Any) {
        
        if let user = Session.getInstance()?.user, let store = self.storeId{
            
            let parameters = [
                "user_id": String(user.id),
                "store_id": String(store),
            ]
            
            let api = SimpleRequestApi()
            Utils.printDebug("\(Constances.Api.API_SAVE_STORE)")
            api.run(url: Constances.Api.API_SAVE_STORE, parameters: parameters) { (parser) in
                
                if parser?.success==1{
                    
                    SavedStores.save(id: store)
                    
                    if let ss = SavedStores.getInstance(){
                        Utils.printDebug("\(ss)")
                    }
                    
                    UIView.animate(withDuration: 0.15) {
                        self.unsaveBtn.isHidden = false
                        self.saveBtn.isHidden = true
                        self.btnsContainer.layoutIfNeeded()
                    }

                    
                }else{
                    UIView.animate(withDuration: 0.15) {
                        self.unsaveBtn.isHidden = true
                        self.saveBtn.isHidden = false
                        self.btnsContainer.layoutIfNeeded()
                    }
                }
            }
            
        }else{
            
            if let store = self.storeId{
                SavedStores.save(id: store)
                
                if let ss = SavedStores.getInstance(){
                    Utils.printDebug("\(ss)")
                }
            }
            
        }
        
        UIView.animate(withDuration: 0.15) {
            self.unsaveBtn.isHidden = false
            self.saveBtn.isHidden = true
            self.btnsContainer.layoutIfNeeded()
        }
        
    }
    
 
    @IBAction func unsaveAction(_ sender: Any) {
        
        if let user = Session.getInstance()?.user, let store = self.storeId{
            
            let parameters = [
                "user_id": String(user.id),
                "store_id": String(store),
            ]
            
            let api = SimpleRequestApi()
            Utils.printDebug("\(Constances.Api.API_REMOVE_STORE)")
            api.run(url: Constances.Api.API_REMOVE_STORE, parameters: parameters) { (parser) in
                
                if parser?.success==1{
                    
                    SavedStores.remove(id: store)
                    
                    if let ss = SavedStores.getInstance(){
                        Utils.printDebug("\(ss)")
                    }
                    
                    UIView.animate(withDuration: 0.15) {
                        self.unsaveBtn.isHidden = true
                        self.saveBtn.isHidden = false
                        self.btnsContainer.layoutIfNeeded()
                    }
                   
                    
                }else{
                    UIView.animate(withDuration: 0.15) {
                        self.unsaveBtn.isHidden = false
                        self.saveBtn.isHidden = true
                        self.btnsContainer.layoutIfNeeded()
                    }
                }
            }
            
        }else{
            
            if let store = self.storeId{
                SavedStores.remove(id: store)
                
                if let ss = SavedStores.getInstance(){
                    Utils.printDebug("\(ss)")
                }
            }
            
        }
        
        UIView.animate(withDuration: 0.15) {
            self.unsaveBtn.isHidden = true
            self.saveBtn.isHidden = false
            self.btnsContainer.layoutIfNeeded()
        }
        
        
    }
    
    
  
    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)
       
        //more options icon
        let menuImage = UIImage.init(icon: .ionicons(.androidMoreVertical), size: CGSize(width: 30, height: 30), textColor: Colors.darkColor)
        let moreBarButtonItem = UIBarButtonItem(image: menuImage, style: .plain, target: self, action: #selector(handleMore))
        moreBarButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: color)
        navigationBarItem.rightBarButtonItems?.append(moreBarButtonItem)
        
    }
    
    
    
    lazy var optionsLauncher: OptionsLauncher = {
        let launcher = OptionsLauncher()
        launcher.delegate = self
        return launcher
    }()
    
    
    @objc func handleMore() {
        
        optionsLauncher.clear()
        
        
        optionsLauncher.addBottomMenuItem(option: Option(
            id: 1110,
            name: "Rate".localized,
            image: optionsLauncher.createIcon(.googleMaterialDesign(.starBorder)),
            object: []
        ))
       
        
        if let store = self.store, !store.saved{
            optionsLauncher.addBottomMenuItem(option: Option(
                id: 1112,
                name: "Add to bookmark".localized,
                image: optionsLauncher.createIcon(.googleMaterialDesign(.bookmarkBorder)),
                object: []
            ))
        }else{
            
            optionsLauncher.addBottomMenuItem(option: Option(
                id: 1113,
                name: "Remove from bookmark".localized,
                image: optionsLauncher.createIcon(.googleMaterialDesign(.bookmark)),
                object: []
            ))
        }
        
        optionsLauncher.addBottomMenuItem(option: Option(
            id: 1114,
            name: "Share".localized,
            image: optionsLauncher.createIcon(.googleMaterialDesign(.share)),
            object: []
        ))
        
       
        optionsLauncher.addBottomMenuItem(option: Option(
            id: 1111,
            name: "Report".localized,
            image: optionsLauncher.createIcon(.ionicons(.androidWarning)),
            object: []
        ))
        
        
        optionsLauncher.load()
        optionsLauncher.showOptions()
        
    }
    
    func onOptionItemPressed(option: Option) {
        
        if option.id == 1111{
            
            guard Session.isLogged() else {
                self.startLoginVC()
                return
            }
            
            guard let sess = Session.getInstance(), let user = sess.user else {
                return
            }
            
            guard let id = self.storeId, let store = Store.findById(id: id) else {
                return
            }
            
            let reporto  = ReportObject(
                title: "Reported Store: "+store.name,
                link: " ("+AppConfig.Api.base_url+"/dashboard/store/all_stores?id=/\(store.id)) \(store.name)",
                owner_user_id: store.user_id,
                reported_by_user_id: user.id
            )
            
            OCReportController.startVC(controller: self,ro: reporto)
        }else if option.id == 1112{
            saveAction(self)
        }else if option.id == 1113{
            unsaveAction(self)
        }else if option.id == 1114{
            onSharehHandle()
        }else if option.id == 1110{
            onRatehHandle()
        }
       
    }
    
    
    func startLoginVC() {

        let sb = UIStoryboard(name: "Login", bundle: nil)
        if sb.instantiateInitialViewController() != nil {

            let ms: LoginViewController = sb.instantiateViewController(withIdentifier: "loginVC") as! LoginViewController
            
            
           self.present(ms, animated: true)
        }

    }
    
    @objc func onSharehHandle()  {
        
        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)
            
        }
        
    }
    
    @objc func onBackHandler()  {
        self.dismiss(animated: true)
    }
    
    @objc func onRatehHandle() {
        
        if !Session.isLogged(){
            let login_cv = LoginViewController.newInstance()
            self.present(login_cv, animated: true)
            return
        }
        
        let sb = UIStoryboard(name: "RateDialog", bundle: nil)
        if let vc = sb.instantiateInitialViewController() {
            let rateDialog: RateDialogViewController = vc as! RateDialogViewController

            rateDialog.store_id = storeId
            rateDialog.delegate = self
        
            self.present(rateDialog, animated: true, completion: nil)
        }
        
    }
    
    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 = true
        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
        
        self.scrollView.parallaxHeader.view = self.imageContainer
        self.scrollView.parallaxHeader.height = self.imageView.frame.height;
        self.scrollView.parallaxHeader.mode = .fill;
        self.scrollView.parallaxHeader.minimumHeight = 0;
        
        if Device.isNotched {
            self.scrollView.parallaxHeader.height = self.imageView.frame.height-24;
         }else{
             self.scrollView.parallaxHeader.height = self.imageView.frame.height;
        }

        //distance tag
        self.distance_label.initDefaultFont(size: 12)
        
        self.featured.leftTextInset = 15
        self.featured.rightTextInset = 15
        self.featured.bottomTextInset = 10
        self.featured.topTextInset = 10
        self.featured.backgroundColor = Colors.featuredTagColor
        self.featured.isHidden = true
        self.featured.initItalicFont()
        
        
        self.open_store_badge.layer.cornerRadius = self.open_store_badge.frame.height/3
        self.open_store_badge.layer.masksToBounds = true
        self.open_store_badge.backgroundColor = .orange
        self.open_store_badge.leftTextInset = 8
        self.open_store_badge.rightTextInset = 8
        //text color & font
        self.open_store_badge.textColor = .white
        self.open_store_badge.textAlignment = .center
        self.open_store_badge.initBolodFont(size: 12)
        
        
        //products tag
        self.last_product.leftTextInset = 15
        self.last_product.rightTextInset = 15
        self.last_product.topTextInset = 10
        self.last_product.bottomTextInset = 10
        self.last_product.backgroundColor = Colors.primaryColor
        self.last_product.initDefaultFont()
        self.last_product.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.websiteBtn.setIcon(icon: .ionicons(.androidGlobe), 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.websiteBtn.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.imageView.layoutIfNeeded()
        //self.slideShow.isHidden = true
        
        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.initBolodFont()
        self.featured.text = "Featured".localized.uppercased()
        
        self.category.textColor = .white
        self.category.initBolodFont()
        self.storeAddress.initDefaultFont()
        self.detailLabel.initBolodFont()
        self.detailLabel.numberOfLines = 0

        self.opening_time_label.text = "Opening time".localized
        self.opening_time_label.initBolodFont()
        self.opening_time_container.isHidden = true
   
        self.opening_time_sub_container.backgroundColor = .white
        self.opening_time_sub_container.roundCorners(radius: 10)
        self.opening_time_sub_container.layer.masksToBounds = true
        
      
    }

    
    @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 SavedStores.exist(id: id) == true{
                self.saveBtn.isHidden = true
                self.unsaveBtn.isHidden = false
            }else{
                self.saveBtn.isHidden = false
                self.unsaveBtn.isHidden = true
            }
            
    
            let distance = store.distance.calculeDistance()
            self.distance_label.text = distance.getCurrent()
            
            
            if  let cobj = Category.findById(id: store.category_id){
                self.category.text = cobj.nameCat
                
                if let image = cobj.images {
                    
                    let url = URL(string: image.url500_500)
                    
                    self.imageCategory.contentMode = .scaleAspectFill
                    self.imageCategory.kf.indicatorType = .activity
                    self.imageCategory.kf.setImage(with: url,options: [.transition(.fade(0.2))])
                    
                }else{
                    if let img = UIImage(named: "default_store_image") {
                        self.imageCategory.image = img
                    }
                }
                
            }else{
                self.category.isHidden = true
            }
            
            
            
            //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
            }
            
            if MyLocation.isProvided{
                self.distance_label.isHidden = false
            }else{
                self.distance_label.isHidden = true
            }
  
            
            if store.nbrOffers > 0{
                setup_recent_offers(store_id: store.id)
            }else{
                recent_offers_container.isHidden = true
                recent_offers_cv.isHidden = true
            }
            
            if store.nbrProducts > 0{
                setup_recent_products(store_id: store.id)
            }else{
                recent_products_container.isHidden = true
                recent_product_cv.isHidden = true
            }
            
            self.setup_opening_time(store: store)
            
            self.setupSocialMediaButtons(store: store)
            
        }else{
            //sync with server
            load()
        }
        
    }
    
    
    func setupSocialMediaButtons(store:Store){
        
        if(store.social_media != ""){
            socialMediaBtn.isHidden = false
           
            socialMediaBtn.setCustomButtonControlStyle()
    
            if(store.social_media.contains("facebook")){
                socialMediaBtn.setIcon(icon: .ionicons(.socialFacebook), iconSize: 24, color:  Colors.primaryColor, forState: .normal)
            }else if(store.social_media.contains("twitter")){
                socialMediaBtn.setIcon(icon: .ionicons(.socialTwitter), iconSize: 24, color:  Colors.primaryColor, forState: .normal)
            }else if(store.social_media.contains("instagram")){
                socialMediaBtn.setIcon(icon: .ionicons(.socialInstagram), iconSize: 24, color:  Colors.primaryColor, forState: .normal)
            }else if(store.social_media.contains("linkedin")){
                socialMediaBtn.setIcon(icon: .ionicons(.socialLinkedin), iconSize: 24, color:  Colors.primaryColor, forState: .normal)
            }else if(store.social_media.contains("youtube")){
                socialMediaBtn.setIcon(icon: .ionicons(.socialYoutube), iconSize: 24, color:  Colors.primaryColor, forState: .normal)
            }else if(store.social_media.contains("wa.me")){
                socialMediaBtn.setIcon(icon: .ionicons(.socialWhatsapp), iconSize: 24, color:  Colors.primaryColor, forState: .normal)
            }else{
                socialMediaBtn.setIcon(icon: .ionicons(.socialFacebook), iconSize: 24, color:  Colors.primaryColor, forState: .normal)
            }
            
        }else{
            socialMediaBtn.isHidden = true
        }
        
    }
    
    
    
    
    func setup_opening_time(store: Store) {
        
        /*
        * OPENING CLOSING TIME TABLE
        */

        if store.opening == 1{
            
            let icon = UIImage.init(icon: .ionicons(.clock), size: CGSize(width: 18, height: 18), textColor: .white)
            self.open_store_badge.text = " \("Open".localized)"
            self.open_store_badge.setLeftIcon(image: icon)
            self.open_store_badge.backgroundColor = .greenSea
            
            self.open_store_badge.isHidden = false
            self.opening_time_container.isHidden = false
            
        }else if store.opening == -1 {
           
            let icon = UIImage.init(icon: .ionicons(.clock), size: CGSize(width: 18, height: 18), textColor: .white)
            self.open_store_badge.text = " \("Closed".localized)"
            self.open_store_badge.setLeftIcon(image: icon)
            self.open_store_badge.backgroundColor = .orange
            
            self.open_store_badge.isHidden = false
            self.opening_time_container.isHidden = false
            
        }else{
            
            self.open_store_badge.isHidden = true
            self.opening_time_container.isHidden = true
            
        }
        
        

        if(store.opening == 1 || store.opening == -1){

            var hours_text = ""
            for opt: OpeningTime in store.opening_time_table_list{

                let opening = DateUtils.getPreparedDateSimple2(dateUTC: "2011-01-01 \(opt.opening)",dateFormat: "h:mm a")
                let closing = DateUtils.getPreparedDateSimple2(dateUTC: "2011-01-01 \(opt.closing)",dateFormat: "h:mm a")
                var day:String = opt.day
                day = day.localized
                day = String(day.prefix(3))
                day = day.capitalizingFirstLetter()

                if(opt.enabled == 1){
                    if(DateUtils.getCurrentDay().lowercased() == opt.day.lowercased() && store.opening == 1){
                        hours_text = hours_text+"<b>\(day)</b>   \(opening) - \(closing)  - <bgreen>\("Open Now".localized)</bgreen>\n"
                    }else if(DateUtils.getCurrentDay().lowercased() == opt.day.lowercased() && store.opening == -1){
                        hours_text = hours_text+"<b>\(day)</b>   \(opening) - \(closing)  - <bred>\("Closed Now".localized)</bred>  \n"
                    }else{
                        hours_text = hours_text+"<b>\(day)</b>   \(opening) - \(closing) \n"
                    }
                }else{
                    hours_text = hours_text+"<b>\(day)</b>   -- \n"
                }


            }

             let attributedStringOPT  = hours_text.toHtml().attributedString

            self.opening_time_text_view.attributedText = attributedStringOPT
            let he = self.opening_time_text_view.frame.height
      
        
        }

        /*
        * END OPENING CLOSING TIME TABLE
        */

    }
    
    func setup_recent_offers(store_id: Int) {
        
        let style = CardHorizontalStyle(width: 360, height: 220, type: .Recent_Offers,title: "recent_offers")
        
        let mProducts_HCards_instance = (Offers_HCards.newInstance(style: style) as! Offers_HCards)
        mProducts_HCards_instance.h_label.text = "recent_offers".localized
        mProducts_HCards_instance.viewTabBarController = self.tabBarController
        mProducts_HCards_instance.__req_store = store_id
        mProducts_HCards_instance.load()
       // mProducts_HCards_instance.delegate = self
                           
        if let title = style.Title{
            mProducts_HCards_instance.h_label.text = title.localized
        }
        
        if let controller = self.navigationController{
            mProducts_HCards_instance.viewNavigationController = controller
        }else{
             mProducts_HCards_instance.viewController = self
        }
    
        recent_offers_container.backgroundColor = .clear
        recent_offers_container.addSubview(mProducts_HCards_instance)
        recent_offers_container.addConstraintsWithFormat(format: "H:|[v0]|", views: mProducts_HCards_instance)
        recent_offers_container.addConstraintsWithFormat(format: "V:|[v0]|", views: mProducts_HCards_instance)
        
        UIView.animate(withDuration: 0.2, delay: 1.0, options: .curveEaseOut, animations: {
            
            self.recent_offers_container.heightAnchor.constraint(equalToConstant:  CGFloat(style.height!)).isActive = true
            
            self.view.layoutIfNeeded()
         }, completion: { finished in
           
         })
        
    }

    
    func setup_recent_products(store_id: Int) {
        
        let style = CardHorizontalStyle(width: 220, height: 250, type: .Recent_Products,title: "recent_products")
        
        let mProducts_HCards = (Products_HCards.newInstance(style: style) as! Products_HCards)
        mProducts_HCards.h_label.text = "recent_products".localized
        mProducts_HCards.viewTabBarController = self.tabBarController
        mProducts_HCards.__req_store = store_id
        mProducts_HCards.load()
       // mProducts_HCards_instance.delegate = self
                           
        if let title = style.Title{
            mProducts_HCards.h_label.text = title.localized
        }
        
        if let controller = self.navigationController{
            mProducts_HCards.viewNavigationController = controller
        }else{
            mProducts_HCards.viewController = self
        }
    
        recent_products_container.backgroundColor = .clear
        recent_products_container.addSubview(mProducts_HCards)
        recent_products_container.addConstraintsWithFormat(format: "H:|[v0]|", views: mProducts_HCards)
        recent_products_container.addConstraintsWithFormat(format: "V:|[v0]|", views: mProducts_HCards)
        
        UIView.animate(withDuration: 0.2, delay: 1.0, options: .curveEaseOut, animations: {
            self.recent_products_container.heightAnchor.constraint(equalToConstant:  CGFloat(style.height!)).isActive = true
            self.view.layoutIfNeeded()
         }, completion: { finished in
           
         })
        
    }
    
    
    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.showMain()
       
        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()
    }
    
    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 startReviewsLsit(store_id: Int)  {
        
        let sb = UIStoryboard(name: "ReviewsList", bundle: nil)
        
        if sb.instantiateInitialViewController() != nil {
            
            
            let ms: ReviewsListViewController = sb.instantiateViewController(withIdentifier: "reviewsListVC") as! ReviewsListViewController
            ms.store_id = store_id
            
            self.present(ms, animated: true)
        }
    }
    
    func startProductsLsit(store_id: Int)  {
        
        let sb = UIStoryboard(name: "ResultList", bundle: nil)
        let ms: ResultListViewController = sb.instantiateViewController(withIdentifier: "resultlistVC") as! ResultListViewController
    
        ms.current_module = AppConfig.HomeStruct.Tags.TAG_PRODUCTS
        ms.config.backHome = true
        ms.config.customToolbar = true
    
        ms.request = ListProductView.Request.recent
        ms.parameters["__req_order"] = String(ListProductView.Request.recent)
        ms.parameters["__req_store"] = String(store_id)
        
        //open result
        //tabBarController?.present(ms, animated: true)
        ms.modalPresentationStyle = .fullScreen
        self.present(ms, animated: true)
        
    }
    
    
    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 startProductDetailVC(productId: Int) {
        
        let sb = UIStoryboard(name: "ProductDetail", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: ProductDetailViewController = sb.instantiateViewController(withIdentifier: "productdetailVC") as! ProductDetailViewController
            
            ms.product_id = productId
            
            self.present(ms, animated: true)
        }
        
    }
    
    
    //Gallery Layout
    func onPress(object: Images) {
    
        
    }
    
    
    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
        // slideshowTransitioningDelegate = ZoomAnimatedTransitioningDelegate(slideshowView: self, slideshowController: fullscreen)
        fullscreen.transitioningDelegate = slideshowTransitioningDelegate
        fullscreen.modalPresentationStyle = .fullScreen
        controller.present(fullscreen, animated: true, completion: nil)

        return fullscreen
    }
}

