//
//  OfferDetailViewController.swift
//  NearbyStores
//
//  Created by Amine on 7/10/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import Atributika
import ImageSlideshow
import AssistantKit
import SwiftWebVC
import SwiftEventBus


class OfferDetailViewController: MyUIViewController, EmptyLayoutDelegate,ErrorLayoutDelegate, OfferLoaderDelegate, UIScrollViewDelegate, UITextViewDelegate, QtySelectorDelegate, Products_HCards_Delegate, OptionsDelegate  {
   
   
    
    //Declare User For Current Session
    var myUserSession: User? = nil
    let slideShow = ImageSlideshow()
    
    
    //adview
    @IBOutlet weak var adSubContainer: UIView!
    @IBOutlet weak var adContainer: UIView!
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var stackview: UIStackView!
    @IBOutlet weak var stackViewRightConstraint: NSLayoutConstraint!
    @IBOutlet weak var stackViewLeftConstraint: NSLayoutConstraint!
    @IBOutlet weak var descriptionTextContainer: UIView!
    
    @IBOutlet weak var discounted_products_container: UIView!
    
    
    @IBOutlet weak var descriptionTextView: UITextView!
    @IBOutlet weak var offer_dates_container: UIStackView!
    @IBOutlet weak var offer_dates: EdgeLabel!
    
    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
            }
        }
    }
    
    @IBOutlet weak var imageContainer: UIView!
    //
   
    @IBOutlet weak var descriptionContainer: UIView! //view store
    @IBOutlet weak var descriptionSubContainer: UIView! //subview store

    @IBOutlet weak var offerDetailLabel: UILabel!
    @IBOutlet weak var offer_label: EdgeLabel!
    @IBOutlet weak var distance_label: EdgeLabel!
    @IBOutlet weak var price_container: UIView!
    

    @IBOutlet weak var featured: EdgeLabel!
    @IBOutlet weak var storeAddressSubContainer: UIView!
    @IBOutlet weak var storeAddress: UILabel!
    @IBOutlet weak var countDownSubContainer: UIView!
    @IBOutlet weak var countDownContainer: UIView!
    
    @IBAction func onStoreNameClicked(_ sender: Any) {
        
        if let id = offer_id, let offer = Offer.findById(id: id){
            let sb = UIStoryboard(name: "StoreDetail", bundle: nil)
            if sb.instantiateInitialViewController() != nil {
                
                let ms: StoreDetailViewController = sb.instantiateViewController(withIdentifier: "storedetailVC") as! StoreDetailViewController
                ms.storeId = offer.store_id
                
                self.present(ms, animated: true)
            }
        }
    }
    

    @IBOutlet weak var order_container: UIView!
    @IBOutlet weak var order_button: UIButton!
    
    @IBAction func order_now_action(_ sender: Any) {
        
        if(!Session.isLogged()){
            startLoginVC()
            return
        }
        
        
        guard let id = offer_id, let offer = Offer.findById(id: id) else {
            return
        }
        
        
        let product = offer.copyProduct()
       
        
        if product.stock >= 1 || product.stock == -1{
            
            let view = qtySelector.show(item: product, amount: Double(product.product_value))
            
           
            qtySelector.delegate = self
            
        }else{
            
            
            var order_product = OrderProduct()
            order_product.item = product
            order_product.amount = Double(product.product_value)
            order_product.qty = 1
            
            self.startOrderController(product: order_product)
    
        }
        
    }
    
    
    func startOrderController(product: OrderProduct) {
           
        let sb = UIStoryboard(name: "Order", bundle: nil)
        let ms: OrderViewController = sb.instantiateViewController(withIdentifier: "orderVC") as! OrderViewController
    
        ms.cart = Cart.createCart(id: 2,items: [product])

        self.present(ms, animated: true)
           
    }
    
    
    func onQtySelectorRightPressed(qty: Double) {
        
        if let id = offer_id, let offer = Offer.findById(id: id) {
            
            let product = offer.copyProduct()
           
            var order_product = OrderProduct()
            order_product.item = product
            order_product.amount = Double(product.product_value)
            order_product.qty = Int(qty)
            
            
            if !Cart.hasStore(item0: order_product){
                self.showAlertError(title: "Cart".localized, content: ["err":"couldn't add an item from the different store".localized], msgBnt: "OK".localized)
                return
            }
            
            self.startOrderController(product: order_product)
    
        }
     }
     
     func onQtySelectorLeftPressed(qty: Double) {
       
       
        
     }
    
    
    lazy var qtySelector: QtySelectorView = {
          let launcher = QtySelectorView()
         // launcher.mainController = self
          return launcher
      }()
      
    
    private var lastContentOffset: CGFloat = 0
    
      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)
          }
          
        }
        
    }
    
    func setupViews() {
        
        
        scrollView.delegate = self
        
        self.view.backgroundColor = Colors.highlightedGray
        
        self.stackview.distribution = .fill
        
        scrollView.parallaxHeader.view = self.imageContainer
        scrollView.parallaxHeader.height = self.imageView.frame.height;
        scrollView.parallaxHeader.mode = .fill;
        scrollView.parallaxHeader.minimumHeight = 0;
        
    
        //offers tag
        offer_label.leftTextInset = 15
        offer_label.rightTextInset = 15
        offer_label.topTextInset = 10
        offer_label.bottomTextInset = 10
        offer_label.backgroundColor = Colors.promoTagColor
        offer_label.textColor = .white
        offer_label.initBolodFont(size: 20)
        offer_label.textAlignment = .center
        
        price_container.backgroundColor = Colors.promoTagColor
        price_container.addShadowView()
        
        
        //distance
        distance_label.initDefaultFont()
        distance_label.textColor = .white
        
        
        //offer dates
        offer_dates.leftTextInset = 15
        offer_dates.rightTextInset = 15
        offer_dates.topTextInset = 10
        offer_dates.bottomTextInset = 10
        
        
        
        featured.leftTextInset = 15
        featured.rightTextInset = 15
        featured.bottomTextInset = 10
        featured.topTextInset = 10
        featured.backgroundColor = Colors.featuredTagColor
        featured.isHidden = true
        featured.initItalicFont()
        
        
        offer_dates.initItalicFont()
        storeAddress.initDefaultFont()
        
        
        self.descriptionSubContainer.layer.cornerRadius = 5/UIScreen.main.nativeScale
        self.descriptionSubContainer.layer.masksToBounds = true
        
        
        self.storeAddressSubContainer.layer.cornerRadius = 5/UIScreen.main.nativeScale
        self.storeAddressSubContainer.layer.masksToBounds = 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)
        
    
        //localization
    
        self.offerDetailLabel.text = "Offer Detail".localized
        
        self.featured.initDefaultFont()
        self.featured.text = "Featured".localized.uppercased()
        self.offerDetailLabel.initBolodFont()
        
        
      
        
        
    }
    
    @objc func didTapOnImage() {
        if #available(iOS 13.0, *){
            self.slideShow.presentFullScreenControllerForIos13(from: self)
        }else{
            self.slideShow.presentFullScreenController(from: self)
        }
    }
  
  
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupSize()
        
        if let session = Session.getInstance(), let user = session.user {
            myUserSession = user
        }
        
        self.view.backgroundColor = Colors.bg_gray_100
        
    
        self.navigationBar.isTranslucent = false
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
              
        
       
       
        setupNavBarTitles(title: "Offer detail")
        setupNavBarButtons()
        setupViews()
        
        
        if let id = offer_id, let _ = Offer.findById(id: id){
            self.setupOfferDetail()
        }else{
            load()
        }
        
        
        
    }
    
   
    
    override func viewWillDisappear(_ animated: Bool) {
        OfferDetailViewController.isAppear = false
    
        if let d = countDownView{
            d.stopTimer()
        }
    }
    
    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: 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.offer_id, let offer = Offer.findById(id: id) else {
                return
            }
            
            let reporto  = ReportObject(
                title: "Reported Offer: "+offer.name,
                link: " ("+AppConfig.Api.base_url+"/dashboard/offer/all_offers?id=/\(offer.id)) \(offer.name)",
                owner_user_id: offer.user_id,
                reported_by_user_id: user.id
            )
            
            OCReportController.startVC(controller: self,ro: reporto)
        }else if option.id == 1114{
            onSharehHandle()
        }
       
    }
    
   
    
    @objc func onBackHandler()  {
        self.dismiss(animated: true)
    }
    
    
    @objc func onSharehHandle() {
        
        if let id = offer_id, let offer = Offer.findById(id: id) {
            
            let text = "%@ - Only on %@ \n %@".localized.format(arguments: offer.name,AppConfig.APP_NAME,offer.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)
            
        }
        
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        
       OfferDetailViewController.isAppear = true
    
    }
    
    
    static var isAppear = false
    

    
    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 setupOfferDetail()  {
        
        if let id = offer_id, let offer = Offer.findById(id: id){
            
            self.offerDetailLabel.numberOfLines = 0
            self.offerDetailLabel.text = offer.name
            
            Utils.printDebug("\(offer)")

            let end_at = DateUtils._UTC(date: offer.date_end, fromFormat: DateFomats.defaultFormatTimeUTC, toFormat:  DateFomats.defaultFormatDate)
            offer_dates.text = " \("Ends in".localized) "+end_at

            let date_icon = UIImage.init(icon: .linearIcons(.calendarFull), size: CGSize(width: 24, height: 24), textColor: Colors.primaryColor)
            
            offer_dates.textColor = Colors.primaryColor
            offer_dates.setLeftIcon(image: date_icon)
            
            
            
            if offer.featured == 1 {
                //self.featured.isHidden = false
            }else{
                //self.featured.isHidden = true
            }
            
            
            let distance = offer.distance.calculeDistance()
            self.distance_label.text = distance.getCurrent(type: AppConfig.distanceUnit)
            

            //setup imageview
             //setup imageview
                    var imagesInputs:[InputSource] = []
                      if offer.listImages.count > 0 {
                          
                          
                          for index in 0...offer.listImages.count-1{
                              let url = offer.listImages[index].url500_500
                              if let k = KingfisherSource(urlString: url){
                                   imagesInputs.append(k)
                              }
                          }
                          
                          self.slideShow.setImageInputs(imagesInputs)
                          
                          
                          if let first = offer.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
                          }
                      }
            
            
            if offer.offer_type == "price" {
                
                if let currency = offer.currency {
                    if let pprice = currency.parseCurrencyFormat(price: Float(offer.offer_value)){
                        self.offer_label.text = "Offer for %@".localized.format(arguments: "\(pprice)")
                    }
                }
                
            }else if offer.offer_type == "percent" {
                self.offer_label.text = "%@%%  OFF".localized.format(arguments: "\(Int(offer.offer_value))")
            }else{
                self.offer_label.text = "Promotion".localized
                self.offer_label.isHidden = false
            }
            
            //setup description
            if offer._description != "" {
                
                Utils.printDebug("\(offer._description)")
                //self.descriptionLabel.text = offer._description
             
                
                //description Text View
                
                Utils.printDebug("Height-before: \(self.descriptionSubContainer.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
            
                //self.descriptionTextView.backgroundColor = UIColor.yellow
            
                let attributedString  = offer._description.toHtml().attributedString
                self.descriptionTextView.attributedText = attributedString
                
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    
                    Utils.printDebug("Height-after: \(self.descriptionSubContainer.frame.height)")
                 
                    //ceate a constraint to fix height size
                   self.descriptionSubContainer.translatesAutoresizingMaskIntoConstraints = false
                    
                    let heightConstraint = NSLayoutConstraint(item: self.descriptionSubContainer, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: self.descriptionSubContainer.frame.height)
                    
                    self.descriptionContainer.addConstraints([heightConstraint])
                    self.descriptionContainer.layoutIfNeeded()
                    self.descriptionSubContainer.layoutIfNeeded()
 
                    
                }
                
                
                
            }else{
                self.descriptionContainer.isHidden = true
            }
            
            
        
            let icon = UIImage.init(icon: .googleMaterialDesign(.place), size: CGSize(width: 24, height: 24), textColor: Colors.primaryColor)
            
            self.storeAddress.text = offer.store_name
            
            if Utils.isRTL(){
                self.storeAddress.setRightIcon(image: icon)
            }else{
                self.storeAddress.setLeftIcon(image: icon)
            }
            
            self.storeAddress.textColor = UIColor.gray
           
            
            //store title
            self.setupNavBarTitles(title: offer.name)
            
            //setup order
            self.order_system_setup(offer: offer)
            
            //setup countdouwn
            self.setup_countdown(offer: offer)
            
            //
            self.setup_discounted_products(offer: offer)
            
            if MyLocation.isProvided{
                self.distance_label.isHidden = false
            }else{
                self.distance_label.isHidden = true
            }
            
            
            //mark as view
            self.markView()
         
        }
        
    }
    
    
    func markView()  {
        
        guard let oid = self.offer_id else {
            return
        }
        
        guard Session.isLogged(), let sess = Session.getInstance(), let user = sess.user else {
            return
        }
        
        if let l = LocalData.getValue(key: "\(oid)-\(user.id)", defaultValue: false), l == true{
            return
        }
        
        
        let simpleApi = SimpleRequestApi()
        
        let params = [
            "user_id": "\(user.id)",
            "product_id":"\(oid)"
        ]
        
        simpleApi.run(url: Constances.Api.API_PRODUCT_VIEW_COUNTER, parameters: params) { parser in
            if let p = parser, p.success == 1{
                LocalData.setValue(key: "\(oid)-\(user.id)", value: true)
            }
        }
        
    }
    
    func setup_discounted_products(offer: Offer) {
        
        let style = CardHorizontalStyle(width: 240, height: 240, type: .Recent_Products,title: "discounted_products")
        
        let mProducts_HCards_instance = (Products_HCards.newInstance(style: style) as! Products_HCards)
        mProducts_HCards_instance.h_label.text = "recent_products".localized
        mProducts_HCards_instance.viewTabBarController = self.tabBarController
        mProducts_HCards_instance.__req_parent_id = offer.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
        }
    
        discounted_products_container.backgroundColor = .clear
        discounted_products_container.addSubview(mProducts_HCards_instance)
        discounted_products_container.addConstraintsWithFormat(format: "H:|[v0]|", views: mProducts_HCards_instance)
        discounted_products_container.addConstraintsWithFormat(format: "V:|[v0]|", views: mProducts_HCards_instance)
        
        UIView.animate(withDuration: 0.2, delay: 1.0, options: .curveEaseOut, animations: {
            
            self.discounted_products_container.heightAnchor.constraint(equalToConstant:  CGFloat(style.height!)).isActive = true
            
            self.view.layoutIfNeeded()
         }, completion: { finished in
           
         })
        
    }
    
    //loaded discounted products
    func onProductsLoaded(count: Int) {
        if(count == 0){
            discounted_products_container.isHidden = true
        }
    }
    
    private func order_system_setup(offer: Offer){
        
        
        if !ModuleManager.isEnabled(module: "nsorder"){
            order_container.isHidden = true
            return
        }
            
        
        guard offer.order_enabled == 1 else{
            order_container.isHidden = true
            return
        }
       
       
        self.order_container.isHidden = false
        
        if offer.order_button == "book"{
            order_button.setTitle("Book Now".localized, for: .normal)
        }else if offer.order_button == "order"{
            order_button.setTitle("Order Now".localized, for: .normal)
        }else if offer.order_button == "get"{
            order_button.setTitle("Get Now".localized, for: .normal)
        }else{
            
            if(offer.order_button != ""){
                order_button.setTitle(offer.order_button.localized, for: .normal)
            }else{
                order_button.setTitle("Order", for: .normal)
            }
            
        }
       
        self.order_button.setTitleColor(.white, for: .normal)
        self.order_button.initBoldFont()
        
    
        self.order_button.isHidden = true
        self.order_container.isHidden = true
        
        DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
            self.order_container.addShadowView()
            self.order_container.backgroundColor = .white
            self.order_container.roundCorners(corners: [.topLeft, .topRight], radius: 20)
            self.order_button.setCustomButtonStyleMain()
            self.order_button.isHidden = false
            self.order_container.isHidden = false
        }
      
    }
    
    var countDownView: CountDownView?
    func setup_countdown(offer: Offer) {
        
        offer_dates_container.isHidden = true
    
        guard offer.is_deal == 1 else {
            self.countDownContainer.isHidden = true
            return
        }
        
        
        countDownView = CountDownView()
        countDownSubContainer.backgroundColor = Utils.hexStringToUIColor(hex: AppConfig.Design.Colors.dealColor)
        countDownSubContainer.roundedCorners()
        
        countDownSubContainer.addSubview(countDownView!)
        countDownView!.setup(width: countDownSubContainer.frame.width-50, height: 30)
        countDownView!.translatesAutoresizingMaskIntoConstraints = false
        
       
        var constraints = [NSLayoutConstraint]()
        
        constraints.append(NSLayoutConstraint(
            item: countDownView!,
            attribute: NSLayoutConstraint.Attribute.centerX,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: countDownSubContainer,
            attribute: NSLayoutConstraint.Attribute.centerX,
            multiplier: 1, constant: 0)
        )
        
        constraints.append(NSLayoutConstraint(
            item: countDownView!,
            attribute: NSLayoutConstraint.Attribute.centerY,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: countDownSubContainer,
            attribute: NSLayoutConstraint.Attribute.centerY,
            multiplier: 1, constant: 0)
        )
        
       
      
        countDownSubContainer.addConstraints(constraints)
        countDownView!.setTime(date_end: offer.date_end).runTimer()
              
        
        if(countDownView?.days == 0 &&
            countDownView?.hours == 0 &&
            countDownView?.minutes == 0 &&
            countDownView?.seconds == 0){
            countDownContainer.isHidden = true
        }
    }
    
    var offer_id: Int? = nil
    
    
    //load store
    var offerLoader: OfferLoader = OfferLoader()
    
    func load () {
        
        
        self.offerLoader.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 offer_id = self.offer_id{
                parameters["offer_id"] = String(offer_id)
            }
            
        }
        
        Utils.printDebug("\(parameters)")
        
        self.offerLoader.load(url: Constances.Api.API_GET_OFFERS,parameters: parameters)
        
    }
    
    func success(parser: OfferParser,response: String) {
        
        self.viewManager.showMain()
        
        if parser.success == 1 {
            
            let offers = parser.parse()
            
            if offers.count > 0 {
                
                offers[0].save()
                self.setupOfferDetail()
                
            }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)
    }
    
    var viewManager: LoaderViewManager =  LoaderViewManager()
    
    func setupViewloader()  {
        
        //setup view loader, Error, Empty layouts
        viewManager.setup(parent: view)
        viewManager.getEmptyLayout().delegate = self
        viewManager.getErrorLayout().delegate = self
        
        if Session.isLogged() ==  false {
            
            return
        }else{
            
        }
    }
    
    func onReloadAction(action: EmptyLayout) {
        
    }
    
    func onReloadAction(action: ErrorLayout) {
        
    }
    

    
    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
    }
    
    
    
    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)
           }
           
       }
    
    
    
}

