//
//  HomeView.swift
//  Dealify
//
//  Created by DT Team  on 2/3/21.
//  Copyright © 2021 Amine. All rights reserved.
//

import Foundation
import UIKit
import SwiftEventBus


protocol HomeViewDelegate {
    func searchPressed()
    func onTopLeftPresse()
    func onTopRightPresse()
}

class HomeView : BaseView , UITextFieldDelegate, UITextViewDelegate, ResultListViewControllerDelegate, UIScrollViewDelegate{
    
    
    
    var isNavigationBarHidden = false

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let scrollOffset = scrollView.contentOffset.y
        
        let navigationBarHeight = self.viewController?.navigationController?.navigationBar.frame.height ?? 0
        
        // Check if the scroll offset is greater than or equal to the navigation bar height
        if scrollOffset >= navigationBarHeight {
            // If the navigation bar is hidden, show it
            if isNavigationBarHidden {
                isNavigationBarHidden = false
                self.viewController?.navigationController?.setNavigationBarHidden(false, animated: true)
            }
        } else {
            // If the scroll offset is less than the navigation bar height, hide the navigation bar
            if !isNavigationBarHidden {
                isNavigationBarHidden = true
                self.viewController?.navigationController?.setNavigationBarHidden(true, animated: true)
            }
        }
        
        self.layoutIfNeeded()
        
    }

    
    
    func onSearchButtonPressed(controller: ResultListViewController, type: String, view: UIView, search_dialog_controller: SearchDialogViewController) {
    
        controller.dismiss(animated: true) {
                
        }
        
    }
    
    
    func onSearchResultBackPressed(controller: ResultListViewController, filterCache: SearchDialogViewController.FilterCache) {
        
       
    }
    
    
    var delegate: HomeViewDelegate? = nil
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var imageProfileView: UIImageView!
    @IBOutlet weak var searchField: UITextField!
    @IBOutlet weak var topLeftButton: UIButton!
    @IBOutlet weak var topRightButton: UIButton!
    @IBOutlet weak var searchFilterButton: UIButton!
    @IBOutlet weak var box_search_container: UIView!
    @IBOutlet weak var main_view: UIView!
    @IBOutlet weak var welcomeBackLabel: UILabel!
    @IBOutlet weak var profileNameLabel: UILabel!
    
    
    @IBAction func onProfileAction(_ sender: Any) {
        if let del = delegate{
            del.onTopLeftPresse()
        }
    }
    
    @IBAction func onCartAction(_ sender: Any) {
        if let del = delegate{
            del.onTopRightPresse()
        }
    }
    
    @IBAction func onFilterAction(_ sender: Any) {
        if let del = delegate{
            del.searchPressed()
        }
    }
    
    
    override func fetch(request: String) {
        
        
        layoutIfNeeded()
        
    }
    
    override func setupViews() {
        
        setAppearance()
        setupHeaderView()
        setupRefreshControl()
        setupCards()
        setupProfileViews()
        
        
        scrollView.delegate = self
        
        
        SwiftEventBus.onMainThread(self, name: "onSessionUpdated") { result in
            self.setupProfileViews()
        }
    
    }

    
    func setAppearance() {
        self.main_view.backgroundColor = Colors.iphoneDisplayMode
    }
    
    
    func setupHeaderView(){
    

        self.searchFilterButton.addTarget(self, action: #selector(handleSearchClick), for: .touchUpInside)
        
        //top buttons
        self.topLeftButton.layer.cornerRadius = 5
        self.topRightButton.layer.cornerRadius = 5
        
        //filter button
        self.searchFilterButton.layer.cornerRadius = 5
        
        //seach container
        self.box_search_container.layer.cornerRadius = 5
        
        //labels
        self.welcomeBackLabel.text = "Welcome Back!".localized
        self.welcomeBackLabel.initDefaultFont()
        
        self.profileNameLabel.text = "Guest".localized
        self.profileNameLabel.initBolodFont()
          
        //setup search field
        self.searchField.initDefaultFont()
        self.searchField.placeholder = "Find products...".localized
        self.searchField.inputAccessoryView = setupDoneButtonOnKeyboard()
        self.searchField.keyboardType = .webSearch
        self.searchField.delegate = self
        
      
        
        self.imageProfileView.layer.cornerRadius = 4
        self.imageProfileView.clipsToBounds = true
        //self.imageProfileView.addShadowView()
        
        
        self.topLeftButton.addShadowView0()
        self.topRightButton.addShadowView0()
        self.searchFilterButton.addShadowView0()
        self.box_search_container.addShadowView0()
        
     
    }
    
    func setupProfileViews() {
        
        imageProfileView.image = UIImage(named: "profile_placeholder")
        //labels
        self.welcomeBackLabel.text = "Welcome Back!".localized
        self.welcomeBackLabel.initDefaultFont()
        
        self.profileNameLabel.text = "Guest".localized
        self.profileNameLabel.initBolodFont()
         
        
        guard let sess = Session.getInstance(), let user = sess.user else{
            return
        }
    
        if let image = user.images{
            let url = URL(string: image.url200_200)
            self.imageProfileView.contentMode = .scaleAspectFill
            self.imageProfileView.kf.indicatorType = .activity
            self.imageProfileView.kf.setImage(with: url,options: [.transition(.fade(0.2))])
        }
        
        let d = user.name.split(separator: " ")
        self.profileNameLabel.text = String(d[0])
        
    }
    
    @objc func handleSearchClick() {
        if let del = delegate{
            del.searchPressed()
        }
    }
    
    func setupCards() {
     
        
        let size = AppConfig.Design.homeList.count-1
        
        if size<0{
            return
        }
        
        for index in 0...AppConfig.Design.homeList.count-1{
            
            let style = AppConfig.Design.homeList[index] as! CardHorizontalStyle
           
            guard let _style = style.type else {
                return
            }
            
            let categories = Category.getTopSubCategories()
            Utils.printDebug("\(categories)")
            
            var instance: UIView? = nil
            switch _style {
                
                
                
                 case .TopProductInCategory1:
                
                
                    if(categories.count<1){
                        break;
                    }
                
                     instance = Products_HCards.newInstance(style: style)
                     (instance as! Products_HCards).h_label.text = "Products for %@".localized.format(arguments: categories[0].nameCat)
                     (instance as! Products_HCards).viewController = self.viewController
                     (instance as! Products_HCards).__req_category = categories[0].numCat
                     (instance as! Products_HCards).load()
                     
                     if let title = style.Title{
                         (instance as! Products_HCards).h_label.text = title.localized
                     }
                     
                     break
                
                
                 case .TopProductInCategory2:
                
                    if(categories.count<2){
                        break;
                    }
                
                        
                     instance = Products_HCards.newInstance(style: style)
                     (instance as! Products_HCards).h_label.text = "Products for %@".localized.format(arguments: categories[1].nameCat)
                     (instance as! Products_HCards).viewController = self.viewController
                     (instance as! Products_HCards).__req_category = categories[1].numCat
                     (instance as! Products_HCards).load()
                     
                     if let title = style.Title{
                         (instance as! Products_HCards).h_label.text = title.localized
                     }
                     
                     break
                
                
                 case .TopProductInCategory3:
                
                    if(categories.count<3){
                        break;
                    }
                
                     instance = Products_HCards.newInstance(style: style)
                    (instance as! Products_HCards).h_label.text = "Products for %@".localized.format(arguments: categories[2].nameCat)
                     (instance as! Products_HCards).viewController = self.viewController
                     (instance as! Products_HCards).__req_category = categories[2].numCat
                     (instance as! Products_HCards).load()
                     
                     if let title = style.Title{
                         (instance as! Products_HCards).h_label.text = title.localized
                     }
                     
                     break
                
                
                case .Top_Nearby_Stores:
                    
                    instance = Stores_HCards.newInstance(style: style)
                    (instance as! Stores_HCards).h_label.text = AppConfig.CardTags.TAG_TOP_RATED.localized
                    (instance as! Stores_HCards).viewController = self.viewController
                    
                    if let title = style.Title{
                        (instance as! Stores_HCards).h_label.text = title.localized
                    }
                    
                    break
                    
                    
                case .Nearby_Stores:
                    instance = Stores_HCards.newInstance(style: style)
                    (instance as! Stores_HCards).h_label.text = AppConfig.CardTags.TAG_NEARBY_STORES.localized
                    (instance as! Stores_HCards).viewController = self.viewController
                    
                    if let title = style.Title{
                        (instance as! Stores_HCards).h_label.text = title.localized
                    }
                    
                    break
                    
               
                case .Recent_Products:
                    instance = Products_HCards.newInstance(style: style)
                    (instance as! Products_HCards).h_label.text = AppConfig.CardTags.TAG_RECENT_PRODUCTS.localized
                    (instance as! Products_HCards).viewController = self.viewController
                    (instance as! Products_HCards).load()
                    
                    if let title = style.Title{
                        (instance as! Products_HCards).h_label.text = title.localized
                    }
                    
                    break
                    
                case .Recent_Offers:
                    
                    instance = Offers_HCards.newInstance(style: style)
                    (instance as! Offers_HCards).h_label.text = AppConfig.CardTags.TAG_RECENT_OFFERS.localized
                    (instance as! Offers_HCards).viewController = self.viewController
                    (instance as! Offers_HCards).load()
                    
                    if let title = style.Title{
                        (instance as! Offers_HCards).h_label.text = title.localized
                    }
                    
                    break
                
                    
                case .Nearby_Offers:
                    
                    instance = Offers_HCards.newInstance(style: style)
                    (instance as! Offers_HCards).h_label.text = AppConfig.CardTags.TAG_NEARBY_PRODUCTS.localized
                    (instance as! Offers_HCards).viewController = self.viewController
                    (instance as! Offers_HCards).load()
                    
                    if let title = style.Title{
                        (instance as! Offers_HCards).h_label.text = title.localized
                    }
                    
                    break
                    
                    
            case .Featured_Offers:
                
                instance = Offers_HCards.newInstance(style: style)
                (instance as! Offers_HCards).h_label.text = AppConfig.CardTags.TAG_NEARBY_PRODUCTS.localized
                (instance as! Offers_HCards).viewController = self.viewController
                (instance as! Offers_HCards).load()
                
                if let title = style.Title{
                    (instance as! Offers_HCards).h_label.text = title.localized
                }
                
                break
                
                
            case .Sliders:
                
    
                if(ModuleManager.isEnabled(module: "nsbanner")){
                    instance = Banners_HCards.newInstance(style: style)
                    (instance as! Banners_HCards).viewController = self.viewController
                    (instance as! Banners_HCards).load()
                }
            
                break
                
            case .Delievry:
    
                if(ModuleManager.isEnabled(module: "delivery")){
                    
                    if let app_store = SyncAppConfig.findById(id: "DELIVERY_IOS_LINK")
                       , app_store.getValue(defaultValue: "") != "" {
                        
                        
                        instance = Delivery_HCards.newInstance(style: style)
                        (instance as! Delivery_HCards).viewController = self.viewController
                    }
                  
                }
            
                break
                
                    
                case .FeaturedProducts:
                    
                    instance = Products_HCards.newInstance(style: style)
                    (instance as! Products_HCards).h_label.text = AppConfig.CardTags.TAG_FEATURED_PRODUCTS.localized
                    (instance as! Products_HCards).viewController = self.viewController
                    (instance as! Products_HCards).load()
                    
                    if let title = style.Title{
                        (instance as! Products_HCards).h_label.text = title.localized
                    }
                    
                    break
                
                case .TopSellerProducts:
                    
                    instance = Products_HCards.newInstance(style: style)
                    (instance as! Products_HCards).h_label.text = AppConfig.CardTags.TAG_TOP_SELLER_PRODUCTS.localized
                    (instance as! Products_HCards).viewController = self.viewController
                    (instance as! Products_HCards).load()
                    
                    if let title = style.Title{
                        (instance as! Products_HCards).h_label.text = title.localized
                    }
                    
                    break
            
                case .TopCategories:
                    
                    instance = Categories_HCards.newInstance(style: style)
                    (instance as! Categories_HCards).h_label.text = AppConfig.CardTags.TAG_TOP_CATEGORIES.localized
                    (instance as! Categories_HCards).viewController = self.viewController
                    
                    if let title = style.Title{
                        (instance as! Categories_HCards).h_label.text = title.localized
                    }
                    
                    break
               
                default:
                    
                    break
                
                }
            
            
            if let _view = instance{
                
                if let height = style.height{
                    instance?.heightAnchor.constraint(equalToConstant: CGFloat(height)).isActive = true
                }
                
                
                stackView.addArrangedSubview(_view)
            }
            
        }
        

    }
    
    private let refreshControl = UIRefreshControl()
    
    func setupRefreshControl() {
        
        if #available(iOS 10.0, *) {
            scrollView.refreshControl = refreshControl
        } else {
            scrollView.addSubview(refreshControl)
        }
        
        // Configure Refresh Control
        refreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged)
        
    }
    
    
    @objc private func refreshData(_ sender: Any) {
    
        self.reload()
        refreshControl.endRefreshing()
        
    }
    
    func reload()  {
        
        //stackView.removeAllArrangedSubviews()
        for item in stackView.arrangedSubviews {
           
            if(item is Stores_HCards){
                let g = item as! Stores_HCards
                g.__req_page  = 1
                g.load()
            }
            
            if(item is Products_HCards){
                let g = item as! Products_HCards
                g.__req_page  = 1
                g.load()
            }
            
            if(item is Offers_HCards){
                let g = item as! Offers_HCards
                g.__req_page  = 1
                g.load()
            }
            
            if(item is Categories_HCards){
                let g = item as! Categories_HCards
                g.__req_page  = 1
                g.load()
            }
            
            if(item is Banners_HCards){
                let g = item as! Banners_HCards
                g.__req_page  = 1
                g.load()
            }
            
        }
    }
    
    
    
    
    func setupDoneButtonOnKeyboard() -> UIToolbar
    {
        let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x:0, y:0, width:320, height:50))
        doneToolbar.barStyle = UIBarStyle.default

     let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
     let done: UIBarButtonItem = UIBarButtonItem(title: "Done".localized, style: UIBarButtonItem.Style.done, target: self, action: #selector(doneButtonAction))

        let items = NSMutableArray()
        items.add(flexSpace)
        items.add(done)

        doneToolbar.items = items as? [UIBarButtonItem]
        doneToolbar.sizeToFit()
        
        return doneToolbar
       
    }

    @objc func doneButtonAction()
    {
        searchField?.resignFirstResponder()
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        
        if let q = textField.text{
            launchResultController(query: q)
        }
        
        return false
    }
    
    
    private func launchResultController(query: String){
        
        
        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
    
        
        //register delegate for this controller to manage it from this controller
        ms.delegate = self
        
        //set order
        ms.request = ListStoresView.Request.recent
        ms.parameters["__req_order"] = ListProductView.Request.recent
        ms.parameters["__req_search"] = query
        
        
        Utils.printDebug("__req_order => \(ms.parameters)")
       
        //open result
        if let vc = self.viewController{
            vc.present(ms, animated: true)
        }
        
        
    }
    
    
    
}
