//
//  ViewController.swift
//  NearbyStores
//
//  Created by Amine on 5/19/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import SwiftIcons
import SwiftEventBus
import UserNotifications
import AssistantKit
import CoreLocation
import RealmSwift
import BadgeSwift
import SwiftWebVC


class MyUITabBarController : UITabBarController {
    
    struct ViewControllerConfig {
        var toolbar: Bool = true
        var backHome: Bool = true
    }
    
    var config: ViewControllerConfig = ViewControllerConfig()
    
    override func viewDidLoad() {
        InComingDataParser.openViewEventBus(controller: self)
    }
    
    
}


class MyUICollectionViewController: UICollectionViewController {
    override func viewDidLoad() {
        InComingDataParser.openViewEventBus(controller: self)
        if #available(iOS 13.0, *) {
            overrideUserInterfaceStyle = .light
        }
    }
}

class MyUIViewController: UIViewController {
    
    struct ViewControllerConfig {
           var customToolbar: Bool = true
           var backHome: Bool = true
           var custom_title: String? = nil
       }
       
    var config: ViewControllerConfig = ViewControllerConfig()

    
    override func viewDidLoad() {
        InComingDataParser.openViewEventBus(controller: self)
        if #available(iOS 13.0, *) {
            overrideUserInterfaceStyle = .light
        }
        

    }
}

class MainViewController: MyUIViewController, UICollectionViewDelegateFlowLayout, MenuBarDelegate, CategoryLoaderDelegate, CLLocationManagerDelegate, LoginControllerDelegate, SearchDialogViewControllerDelegate, ResultListViewControllerDelegate, HomeViewDelegate, SettingsLauncherDelegate, EditProfileControllerDelegate {
   
    
    func editProfilSuccess(controller: EditProfileViewController, user: User) {
        
    }
    
    func editProfileFaild(controller: EditProfileViewController) {
        
    }
    
    func onBackPressed(controller: EditProfileViewController) {
        SwiftEventBus.post("onSessionUpdated", sender: true)
    }
    
    func onItemPressed(setting: Setting) {
        
        if setting.id == MenuIDList.CATEGORIES{
            
            startCategoriesList()
            
        }else if setting.id == MenuIDList.WALLET{
            
            if Session.isLogged() {
                startWalletVC()
            }else{
                startLoginVC()
            }
            
        }else if setting.id == MenuIDList.LOGOUT{
            
            if Session.logout() {
                self.settingsLauncher.load()
            }
            
            
            SwiftEventBus.post("onSessionUpdated", sender: true)
            
        }else if setting.id == MenuIDList.CHAT_LOGIN{
            if Session.isLogged() == false {
                if let vc = MainViewController.mInstance {
                    vc.startLoginVC()
                }
            }else{
               startDiscussion()
            }
        }else if setting.id == MenuIDList.PEOPLE_AROUND_ME {
            
            let sb = UIStoryboard(name: "PeopleList", bundle: nil)
            
            if sb.instantiateInitialViewController() != nil {
                
                let vc: PeopleListViewController = sb.instantiateViewController(withIdentifier: "peopleVC") as! PeopleListViewController
                navigationController?.present(vc, animated: true)
            }
            
        }else if setting.id == MenuIDList.GEO_STORES {
            
            let sb = UIStoryboard(name: "GeoStore", bundle: nil)
            if let vc = sb.instantiateInitialViewController() {
                navigationController?.present(vc, animated: true)
            }
            
        }else if setting.id == MenuIDList.MY_ORDERS {
            
            if(Session.isLogged()){
                OrdersListController.startController(viewController: navigationController!)
            }else{
                startLoginVC()
            }
            
        }else if setting.id == MenuIDList.FAVOURITES {
            
            // Bookmark view
            let vc = MyFavoritesViewController.newInstance()
            
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
            
        }else if setting.id == MenuIDList.EDIT_PROFILE {
            
            if Session.isLogged(){
                startEditProfileVC()
            }else{
                startLoginVC()
            }
            
        }else if setting.id == MenuIDList.ABOUT {
            
             startAboutVC()
            
        }else if setting.id == MenuIDList.SETTING {
            
            self.startSettingVC()
            
        }else if setting.id == MenuIDList.MANAGE_STORES{
            
            startBusinessManager()
            
        }
    }
    
   
    
    
  

    
    func loginSuccess(controller: LoginViewController, user: User) {
        
        Session.createSession(user: user)
        count_notifications()
    

        controller.dismiss(animated: true)
        
     
        //session updated
        SwiftEventBus.post("onSessionUpdated", sender: true)
    

    }
    
    
    func startSplash(){
        
        let sb = UIStoryboard(name: "Splash", bundle: nil)
        let vc: SplashViewController = sb.instantiateViewController(withIdentifier: "splash") as! SplashViewController
        
        vc.modalPresentationStyle = .fullScreen
        self.present(vc, animated: true)
        
    }
    
    func loginFaild(controller: LoginViewController) {
         controller.dismiss(animated: true)
    }
    
    
    
    
    let locationManager = CLLocationManager()
    var currentLocation: CLLocationCoordinate2D? = nil
    
    
    private var nbr_location_requests = 0
     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
           
           guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
           
           self.currentLocation = locValue
           
           Utils.printDebug("Location \(locations)")
           
           if let guest = Guest.getInstance(), let cl = self.currentLocation {
               
             Utils.printDebug("Location-guest \(guest)")
               
               let realm = try! Realm()
               try! realm.write {
                   
                   guest.lat = cl.latitude
                   guest.lng = cl.longitude
                   realm.add(guest,update: .all)
                   
               }
            
                    if guest.lat == 0 && guest.lng == 0{
                        MyLocation.isProvided = false
                    }else{
                        MyLocation.isProvided = true
                    }
               
               if(nbr_location_requests>15){
                 self.locationManager.stopUpdatingLocation()
               }
               
               self.nbr_location_requests = self.nbr_location_requests+1
           }
           
       }
    
    
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        
        
        if CLLocationManager.locationServicesEnabled() {
            switch CLLocationManager.authorizationStatus() {
            case .notDetermined, .restricted, .denied:
                self.requestLocation()
            case .authorizedAlways, .authorizedWhenInUse:
                self.requestLocation()
            }
        }
        
        
    }
    
    func requestLocation() {
        
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    
        
    }
  
    
    private func setTitleForIndex(index: Int) {
        if let titleLabel = navigationItem.titleView as? UILabel {
            
            if index == 0 {
                titleLabel.text = "Home".localized
            }else{
                titleLabel.text = "\(AppConfig.HomeStruct.Pages[index].localized.capitalizingFirstLetter())"
            }
            
        }
    }
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = "Home".localized
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        
        return titleLabel
        
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        
        //update location
        self.locationManager.delegate = self
        self.requestLocation()
        

        self.loadCategories()
     
        MainViewController.mInstance = self
        
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: .black)
        navigationController?.navigationBar.backgroundColor = .white
       
        
        
        
    
        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: .black)
        topBarTitle.initDefaultFont(size: 17)
        
        topBarTitle.leftTextInset = 5
        topBarTitle.rightTextInset = 5
    

        navigationItem.titleView = topBarTitle
        UIApplication.shared.statusBarView?.backgroundColor = Colors.darkColor
        self.view.backgroundColor = .white
       
        setupMenuBar()
        setupMainViewContainer()
       
   
        setupNavBarButtons()
        busEventsListiner()
        updateInboxBadge(count: Messenger.nbrMessagesNotSeen)
    
        //get notifications count from server
        count_notifications()
        
        count_cart()
        
    }
    

    //search pressed action delegated from HomeViews
    func searchPressed() {
        self.handleSearchClick()
    }
    
    
    func onTopLeftPresse() {
        settingsLauncher.showSettings()
    }
    
    func onTopRightPresse() {
        
        didOnTapCart()
        
    }
    
    func count_cart() {
        
        if let cart = Cart.find(){
            self.updateCartBadge(count: cart.items.count)
        }else{
            self.updateCartBadge(count: 0)
        }
    }
    
   /* var interstitial: GADInterstitial!
    
    func showInterstitial()  {
        if interstitial.isReady{
            interstitial.present(fromRootViewController: self)
        }
    }*/
    
    func busEventsListiner() {
        
       
        SwiftEventBus.onMainThread(self, name: "on_main_refresh") { result in
            
            if let _ = result?.object{
                self.settingsLauncher.load()
            }
            
        }
        
        SwiftEventBus.onMainThread(self, name: "on_badge_refresh") { result in
            
            if let _ = result?.object{
                
                self.updateInboxBadge(count: Messenger.nbrMessagesNotSeen)
                
            }
            
        }
        
        
        SwiftEventBus.onMainThread(self, name: "on_main_redirect") { result in
            
            if let index = result?.object{
                
                let indexPath = IndexPath(item: index as! Int, section: 0)
                
                self.setTitleForIndex(index: index as! Int)
                self.menuBar.collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
                self.menuBar.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .left)

            }
            
        }
        
        SwiftEventBus.onMainThread(self, name: "on_receive_message") { result in
            
            if let object = result?.object{
                
                
                if Session.isLogged() {
                    
                    let message: Message = object as! Message
                    message.save()
                    
                    guard MessengerViewController.isAppear == false else {
                        Messenger.nbrMessagesNotSeen = 0
                        self.updateInboxBadge(count: Messenger.nbrMessagesNotSeen)
                        return
                    }
                    
                    Messenger.nbrMessagesNotSeen += 1
                    
                    self.updateInboxBadge(count: Messenger.nbrMessagesNotSeen)
                    
                    if Messenger.nbrMessagesNotSeen == 1 {
                        
                        NotificationManager.push(
                            title: "New Message".localized,
                            subtitle: message.message,
                            identifier: InComingDataParser.tag_new_message
                        )
                        
                    }else if Messenger.nbrMessagesNotSeen > 1 &&  Messenger.nbrMessagesNotSeen < 3 {
                        
                        NotificationManager.push(
                            title: AppConfig.APP_NAME,
                            subtitle: "You have %@ messages".localized.format(arguments: String(Messenger.nbrMessagesNotSeen)),
                            identifier: InComingDataParser.tag_new_message
                        )
                        
                    }
                    
                }
                
            
                
            }
            
            
     
            
            SwiftEventBus.onMainThread(self, name: "on_home_reload") { result in
                
                if let index = result?.object{
                    
                    if let home: HomeView = self.list_views[AppConfig.HomeStruct.Tags.TAG_HOME] as? HomeView{
                        home.reload()
                    }

                }
                
            }
        }
        
        
        SwiftEventBus.onMainThread(self, name: "decrease_notifications_badge") { result in
            
            guard let b = self.notifBarButtonItem else {
                return
            }
            
            let button: BadgeButton = b.customView as! BadgeButton
            
            if(button.notification>0){
                self.updateNotificationBadge(count: button.notification-1)
            }else{
                self.updateNotificationBadge(count: 0)
            }
            
        }
        
        
        SwiftEventBus.onMainThread(self, name: "increase_notifications_badge") { result in
            
            guard let b = self.notifBarButtonItem else {
                return
            }
            
            let button: BadgeButton = b.customView as! BadgeButton
            
            if(button.notification>0){
                self.updateNotificationBadge(count: button.notification+1)
            }else{
                self.updateNotificationBadge(count: 0)
            }
            
        }
        
     
        
        SwiftEventBus.onMainThread(self, name: "update_cart_badge") { result in
            
            guard let b = self.cartBarButtonItem else {
                return
            }
            
            let button: BadgeButton = b.customView as! BadgeButton
            
            if let cart = Cart.find(){
                self.updateCartBadge(count: cart.items.count)
            }else{
                self.updateCartBadge(count: 0)
            }
           
            
        }
    }
    

    
    static var isAppear = false
    override func viewWillDisappear(_ animated: Bool) {
        MainViewController.isAppear = false
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
         MainViewController.isAppear = true
    }
    
    
    var searchBarButtonItem: UIBarButtonItem? = nil
    var moreBarButtonItem: UIBarButtonItem? = nil
    var notifBarButtonItem: UIBarButtonItem? = nil
    var cartBarButtonItem: UIBarButtonItem? = nil
    
    
    func setupNavBarButtons() {
        
        let color = AppDesignUtils.defaultModeColor(dark: .white, light: .black)
       
    
        //setup more icon btn
        let moreIcon = UIImage.init(icon: .linearIcons(.list), size: CGSize(width: 30, height: 30), textColor: color)
        moreBarButtonItem = UIBarButtonItem(image: moreIcon, style: .plain, target: self, action: #selector(handleMore))
        
        
        //setup notification icon btn
        let notificationBadge = BadgeButton()
        notificationBadge.setIcon(icon: .linearIcons(.alarm), iconSize: 24, color: color, forState: .normal)
        notificationBadge.setupBadge().refreshBadge(count: 0)
        notificationBadge.addTarget(self, action: #selector(didOnTapNotification), for: .touchUpInside)
        notifBarButtonItem = UIBarButtonItem(customView: notificationBadge)
        
        
        //setup notification icon btn
        
        if( ModuleManager.isEnabled(module: "nsorder")){
            let cartBadge = BadgeButton()
            cartBadge.setIcon(icon: .linearIcons(.cart), iconSize: 24, color: color, forState: .normal)
            cartBadge.setupBadge().refreshBadge(count: 1)
            cartBadge.addTarget(self, action: #selector(didOnTapCart), for: .touchUpInside)
            cartBarButtonItem = UIBarButtonItem(customView: cartBadge)
        }
        
        
        //setup more icon btn
        let magnifierIcon = UIImage.init(icon: .linearIcons(.magnifier), size: CGSize(width: 30, height: 30), textColor: color)
        searchBarButtonItem = UIBarButtonItem(image: magnifierIcon, style: .plain, target: self, action: #selector(handleSearchClick))
        
        
        
        navigationItem.rightBarButtonItems = []
        navigationItem.leftBarButtonItems = []
        
        
        if let btn = moreBarButtonItem{
            navigationItem.leftBarButtonItems?.append(btn)
        }
        
        if let btn = notifBarButtonItem{
            navigationItem.rightBarButtonItems?.append(btn)
        }
        
        if let btn = cartBarButtonItem{
            navigationItem.rightBarButtonItems?.append(btn)
        }
        
      
        let size = AppConfig.HomeStruct.Pages.count-1
        var home = false
        for index in 0...size{
            if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_HOME){
                home = true
                break
            }
        }
           
        if let btn = searchBarButtonItem, home == false{
            navigationItem.rightBarButtonItems?.append(btn)
        }
       
        
    
    }
    
    static var count_notifications = 0
    
    func updateNotificationBadge(count: Int) {
    
        guard let b = notifBarButtonItem else {
            return
        }
        
        let button: BadgeButton = b.customView as! BadgeButton
        button.refreshBadge(count: count)
        
    }
    
    
    func updateCartBadge(count: Int) {
    
        guard let b = cartBarButtonItem else {
            return
        }
        
        let button: BadgeButton = b.customView as! BadgeButton
        button.refreshBadge(count: count)
        
    }
    
    @objc func didOnTapCart() {
        
       let sb = UIStoryboard(name: "CartView", bundle: nil)
        let ms: CartViewController = sb.instantiateViewController(withIdentifier: "cart_vc") as! CartViewController
        ms.parent_controller = self
        self.present(ms, animated: true)
        
    }
    
    
    
    /*
    * FILTER & SEARCH FEATURE SETUP
    */

  
  var filterCache: SearchDialogViewController.FilterCache? = nil
   
    
    @objc func handleSearchClick() {
           
           if let cache = filterCache, let type = cache._type{
                launchSearchDialog(type: type)
           }else{
              
                let module = AppConfig.HomeStruct.Tags.TAG_PRODUCTS
              launchSearchDialog(type: module)
              
           }
          
       }
    
    
    func launchSearchDialog(type: String){
        
        if type == AppConfig.HomeStruct.Tags.TAG_STORES{
            
            let sb = UIStoryboard(name: "SearchDialog", bundle: nil)
            if let vc = sb.instantiateInitialViewController() {
                let searchDialog: SearchDialogViewController = vc as! SearchDialogViewController
                
                let _view = UIView.loadFromNib(name: "StoreSearch")
                searchDialog.setup(type: type, view: _view)
                searchDialog.delegate = self
                
                if let cache = filterCache{
                    searchDialog.filterCache = cache
                }
          
              //searchDialog.sort_checkbox = false
          
              searchDialog.modalPresentationStyle = .fullScreen
              self.present(searchDialog, animated: true)
              
            }
        }else if type == AppConfig.HomeStruct.Tags.TAG_PRODUCTS{
            
            let sb = UIStoryboard(name: "SearchDialog", bundle: nil)
            if let vc = sb.instantiateInitialViewController() {
                let searchDialog: SearchDialogViewController = vc as! SearchDialogViewController
                
                let _view = UIView.loadFromNib(name: "ProductSearch")
                searchDialog.setup(type: type, view: _view)
                searchDialog.delegate = self
                
                if let cache = filterCache{
                    searchDialog.filterCache = cache
                }
              
                  //searchDialog.sort_checkbox = false
                
                 searchDialog.modalPresentationStyle = .fullScreen
                 self.present(searchDialog, animated: true)
                               
            }
            
        }
        
        
    }
    
   
    
    func onSearch(type: String, view: UIView, controller: SearchDialogViewController) {
        
        
        filterCache = SearchDialogViewController.FilterCache()

        filterCache?._type = type
        filterCache?._view = view
        
        
        let sb = UIStoryboard(name: "ResultList", bundle: nil)
        let ms: ResultListViewController = sb.instantiateViewController(withIdentifier: "resultlistVC") as! ResultListViewController
        
        
        ms.current_module = type
        
        if type == AppConfig.HomeStruct.Tags.TAG_STORES{
            
          
            ms.parameters = ms.getParameters(type: type, instance: view)
            
            ms.config.backHome = true
            ms.config.customToolbar = true
            
            //send saved filter
            ms.filterCache = filterCache
            
            //close search dialog
             controller.onBackHandler()
            
            //register delegate for this controller to manage it from this controller
            ms.delegate = self
            
            
            //Sort parameters DATE - GEO
            if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO
                && SearchDialogViewController.listing_custom_location_enabled){
                
      
                ms.parameters["__req_order"] = String(ListStoresView.Request.nearby)
                ms.parameters["__req_loc_latitude"] = "\(SearchDialogViewController.listing_custom_location_latitude)"
                ms.parameters["__req_loc_longitude"] = "\(SearchDialogViewController.listing_custom_location_longitude)"
                
            }else if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO){
                
                ms.request = ListStoresView.Request.nearby
                ms.parameters["__req_order"] = String(ListStoresView.Request.nearby)
              
            }else{
               
                ms.request = ListStoresView.Request.nearby
                ms.parameters["__req_order"] = String(ListStoresView.Request.recent)
               
            }
            
            
            Utils.printDebug("__req_order => \(ms.parameters)")
           
            
            //open result
            //tabBarController?.present(ms, animated: true)
            navigationController?.present(ms, animated: true)
            
        }else if type == AppConfig.HomeStruct.Tags.TAG_PRODUCTS{
            
            ms.parameters = ms.getParameters(type: type, instance: view)
                      
            //ms.delegate = self
            
            ms.config.backHome = true
            ms.config.customToolbar = true
            
            //send saved filter
            ms.filterCache = filterCache
            
            
            //close search dialog
            controller.onBackHandler()
            
            
            //register delegate for this controller to manage it from this controller
            ms.delegate = self
            
            
            //Sort parameters DATE - GEO
            if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO
                           && SearchDialogViewController.listing_custom_location_enabled){
                           
                ms.request = ListProductView.Request.nearby
                ms.parameters["__req_order"] =  String(ListProductView.Request.nearby)
                ms.parameters["__req_loc_latitude"] = "\(SearchDialogViewController.listing_custom_location_latitude)"
                ms.parameters["__req_loc_longitude"] = "\(SearchDialogViewController.listing_custom_location_longitude)"
                           
            }else  if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO){
                                      
                ms.request =  ListProductView.Request.nearby
                ms.parameters["__req_order"] = String(ListProductView.Request.nearby)
                                   
            }else{
                          
                ms.request = ListProductView.Request.recent
                ms.parameters["__req_order"] = String(ListProductView.Request.recent)
                          
            }
            
            //open result
            //tabBarController?.present(ms, animated: true)
            navigationController?.present(ms, animated: true)
            
        }
        
    }
    

    
    func onSearchButtonPressed(controller: ResultListViewController, type: String, view: UIView, search_dialog_controller: SearchDialogViewController) {
    
        controller.dismiss(animated: true) {
            self.onSearch(type: type, view: view, controller: search_dialog_controller)
        }
        
    }
    
    
    func onSearchResultBackPressed(controller: ResultListViewController, filterCache: SearchDialogViewController.FilterCache) {
        
        self.filterCache = filterCache
        
    }
    
    
    @objc func didOnTapNotification() {
        
        
        self.startNotificationListVC()
        
        /*if(Session.isLogged()){
            self.startNotificationListVC()
        }else{
        
            let sb = UIStoryboard(name: "Login", bundle: nil)
            if sb.instantiateInitialViewController() != nil {
                let ms: LoginViewController = sb.instantiateViewController(withIdentifier: "loginVC") as! LoginViewController
                ms.delegate = self
                navigationController?.present(ms, animated: true)
            }
        }*/
        
    }
    
    func setupInboxBadge() {
        
    }
    
    
    func updateInboxBadge(count: Int) {
        
        let size = AppConfig.HomeStruct.Pages.count-1
        for index in 0...size{
            if AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_INBOX{
                let indexPath = IndexPath(item: index, section: 0)
                
                let current = IndexPath(item: 0, section: 0)
                menuBar.refreshBadge(at: indexPath, count: count,current: current)
            
            }
        }
    }
   
    
    lazy var settingsLauncher: SettingsLauncher = {
        let launcher = SettingsLauncher()
        launcher.mainController = self
        launcher.delegate = self
        return launcher
    }()
    
    @objc func handleMore() {
        settingsLauncher.showSettings()
    }
    
    func showControllerForSetting(setting: Setting) {
        
      
        
    }
    
    func startBusinessManager()  {
          
          let sb = UIStoryboard(name: "BusinessManager", bundle: nil)
          
          let ms: BusinessManagerViewcController = sb.instantiateViewController(withIdentifier: "busniss_manager_vc") as! BusinessManagerViewcController
          
          ms.config.backHome = true
          ms.config.customToolbar = true
          
          if let controller = self.navigationController{
              controller.pushViewController(ms, animated: true)
          }else{
               self.present(ms, animated: true)
          }
         
         
      }
    
    //avaliable in 14+
    func setupMainViewContainer() {
        
        let container = UIView()
        container.frame = view.bounds
        container.backgroundColor = Colors.bg_gray_100
        view.addSubview(container)
        
        container.translatesAutoresizingMaskIntoConstraints = false
        
        
        if AppConfig.HomeStruct.MenuPosition == .TOP{
            
            let constraints = [
                container.topAnchor.constraint(equalTo: menuBar.bottomAnchor),
                container.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                container.bottomAnchor.constraint(equalTo: view.bottomAnchor),
                container.trailingAnchor.constraint(equalTo: view.trailingAnchor)
            ]
            
            view.addConstraints(constraints)
        
        }else  if AppConfig.HomeStruct.MenuPosition == .BOTTOM{
            
            /*HOME V2*/
            let constraints = [
                container.topAnchor.constraint(equalTo: view.topAnchor),
                container.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                container.bottomAnchor.constraint(equalTo: menuBar.topAnchor),
                container.trailingAnchor.constraint(equalTo: view.trailingAnchor)
            ]
            /*HOME V2 END*/
            
            view.addConstraints(constraints)
        
        }
    
        
        
        let size = AppConfig.HomeStruct.Pages.count-1
        for index in 0...size{
             
            if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_PRODUCTS){
                
                let list = ListProductView()
                list.frame = container.bounds
                container.addSubview(list)
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                view.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
                
    
                list.req_list_style = true
                list.setupViews()
                list.viewController = self
                
                list.isHidden = true
              
                list_views[AppConfig.HomeStruct.Tags.TAG_PRODUCTS] = list
                
            }else  if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_OFFERS){
                
                let list = ListOfferView()
                list.frame = container.bounds
                container.addSubview(list)
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                view.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
                
            
                list.setupViews()
                list.viewController = self
                
                list.isHidden = true
              
                list_views[AppConfig.HomeStruct.Tags.TAG_OFFERS] = list
                
            }else if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_GEO){
                
                let list = GeoStoresView()
                list.frame = container.bounds
                container.addSubview(list)
                container.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                container.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
              
                
                list.setupViews()
                list.viewController = self
                list.isHidden = true
               
                list_views[AppConfig.HomeStruct.Tags.TAG_GEO] = list
                 
            
            }else if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_INBOX){
                
                let list = ListDiscussionView()
                list.frame = container.bounds
                container.addSubview(list)
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                view.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
            
                list.setupViews()
                list.viewController = self
            
                list.isHidden = true
               
                list_views[AppConfig.HomeStruct.Tags.TAG_INBOX] = list
                
            }else if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_STORES){
                
                let list = ListStoresView()
                list.frame = container.bounds
                container.addSubview(list)
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                view.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
            
                list.setupViews()
                list.viewController = self
                list.isHidden = true
               
                list_views[AppConfig.HomeStruct.Tags.TAG_STORES] = list
                
            }else if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_HOME){
                
             
                
                let list: HomeView = UIView.loadFromNib(name: "HomeView") as! HomeView
                list.frame = container.bounds
                container.addSubview(list)
                
                
                //NavigationBar configuration
                let navigationBarHeight = self.navigationController?.navigationBar.frame.height ?? 0
                self.navigationController?.setNavigationBarHidden(true, animated: true)
                list.isNavigationBarHidden = true
               
                
                
                
                
                let topConstraint = NSLayoutConstraint(item: list, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: navigationBarHeight)
                view.addConstraint(topConstraint)
                
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                view.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
            
                
                list.viewController = self
                list.delegate = self
                
                list.setupViews()
                
                list.isHidden = true
                
                list_views[AppConfig.HomeStruct.Tags.TAG_HOME] = list
                
            }else if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_NOTIFICATION){
                
            
                let list = ListNotificationView()
                list.frame = container.bounds
                container.addSubview(list)
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                view.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
            
                list.setupViews()
                list.viewController = self
                list.isHidden = true
               
                list_views[AppConfig.HomeStruct.Tags.TAG_NOTIFICATION] = list
                
                
            }else if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_FAVOURITES){
                
            
                let list = ListBookmarksCell()
                list.frame = container.bounds
                container.addSubview(list)
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                view.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
              
        
            
                list.setupViews()
                list.viewController = self
                list.isHidden = true
               
                list_views[AppConfig.HomeStruct.Tags.TAG_FAVOURITES] = list
                
                
            }else if(AppConfig.HomeStruct.Pages[index] == AppConfig.HomeStruct.Tags.TAG_ACCOUNT){
                
                
                let list = BaseView()
                list.frame = container.bounds
                container.addSubview(list)
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: list)
                view.addConstraintsWithFormat(format: "V:|[v0]|", views: list)
            
                list.setupViews()
                list.viewController = self
                list.isHidden = true
               
                list_views[AppConfig.HomeStruct.Tags.TAG_ACCOUNT] = list
                
                
            }
            
            
        }
        
        activePage(index: 0)
        
    }
    
    var currentPage = 0
    
    private func activePage(index: Int) {
        
        let tab = AppConfig.HomeStruct.Pages[index]
       
        for (_,v) in self.list_views{
            v.isHidden = true
        }
        self.list_views[tab]?.isHidden = false
    
        if(!list_views[tab]!.isFetched){
            if(tab == AppConfig.HomeStruct.Tags.TAG_FAVOURITES){
                
                let view: ListBookmarksCell = list_views[tab] as! ListBookmarksCell
                view.fetch(request: BaseView.Request.defaultRequest)
                view.checker()
                
            }else if(tab == AppConfig.HomeStruct.Tags.TAG_HOME){
                
                
                let homeView: HomeView = list_views[tab] as! HomeView
                homeView.fetch(request: BaseView.Request.defaultRequest)
             
                
            }else{
                list_views[tab]?.fetch(request: BaseView.Request.defaultRequest)
            }
            
        }
        
    }
    
    var list_views: [String: BaseView] = [:]
    
    
    lazy var menuBar: MenuBar = {
        let mb = MenuBar()
        return mb
    }()
    
    private func setupMenuBar(){
        

        if AppConfig.HomeStruct.Pages.count > 1 {
            
            if AppConfig.HomeStruct.MenuPosition == .TOP{
                
               let bgViw = UIView()
                bgViw.backgroundColor = .clear
                
                
                view.addSubview(bgViw)
                
                view.addConstraintsWithFormat(format: "H:|[v0]|", views: bgViw)
                view.addConstraintsWithFormat(format: "V:[v0(50)]", views: bgViw)
                
                menuBar.delegate = self
                
                view.addSubview(menuBar)

                view.addConstraintsWithFormat(format: "H:|[v0]|",views: menuBar)
                view.addConstraintsWithFormat(format: "V:[v0(50)]", views: menuBar)
        
                menuBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
                
                
            }else if AppConfig.HomeStruct.MenuPosition == .BOTTOM{
                
                /*HOME V2*/
                
                menuBar.delegate = self
               
                view.addSubview(menuBar)
                
                menuBar.translatesAutoresizingMaskIntoConstraints = false
                
                let constraints = [
                    //menuBar.topAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor),
                    menuBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                    menuBar.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor),
                    menuBar.trailingAnchor.constraint(equalTo: view.trailingAnchor)
                ]
                
                view.backgroundColor = .white
                
               
                view.addConstraints(constraints)
                
                menuBar.heightAnchor.constraint(equalToConstant: CGFloat(50)).isActive = true
                
                /*HOME V2 END*/
                
            }
            
           
           
            
        }else{
            menuBar.isHidden = true
        }
       
    }
    
    func scrollToMenuIndex(index menuIndex: Int) {
        
        _ = IndexPath(item: menuIndex, section: 0)
        
        let tab = AppConfig.HomeStruct.Pages[menuIndex]
        
        if(tab == AppConfig.HomeStruct.Tags.TAG_ACCOUNT){
            
            //start controller
            self.startProfileVC()
            
        }else{
             setTitleForIndex(index: menuIndex)
            //rendering the current view
            self.activePage(index: menuIndex)
           
        }
        
        
    }
  
    
    static var mInstance: MainViewController? = nil
    
    func startLoginVC() {
        
        let sb = UIStoryboard(name: "Login", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: LoginViewController = sb.instantiateViewController(withIdentifier: "loginVC") as! LoginViewController
            ms.delegate = self
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    
    func startSignUpVC() {
        
        let sb = UIStoryboard(name: "SignUp", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: SignUpViewController = sb.instantiateViewController(withIdentifier: "signupVC") as! SignUpViewController
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    func startEditProfileVC() {
        
        let sb = UIStoryboard(name: "EditProfile", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: EditProfileViewController = sb.instantiateViewController(withIdentifier: "editprofileVC") as! EditProfileViewController
            ms.delegate = self
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    
    func startProfileVC() {
        
        
        let vc = EditProfileV2TabBarController()
        vc.config.backHome = true
        vc.config.toolbar = true
        
        let main = UINavigationController(rootViewController:  vc)
        //self.navigationController?.pushViewController(main, animated: true)
        main.setNavigationBarHidden(true, animated: true)
        main.navigationBar.isHidden = true
    
        self.present(EditProfileV2TabBarController(), animated: true)
    }
    
    
    func startMessenger(client_id: Int,discussion_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
            ms.discussionId = discussion_id
            
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    func startDiscussion() {
        
        let vc = DiscussionViewController.newInstance()
        navigationController?.present(vc, 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
           
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    func startPeopleList() {
        
        let sb = UIStoryboard(name: "PeopleList", bundle: nil)
        
        if sb.instantiateInitialViewController() != nil {
            
            let vc: PeopleListViewController = sb.instantiateViewController(withIdentifier: "peopleVC") as! PeopleListViewController
            navigationController?.present(vc, animated: true)
        }
        
    }
    
    
    func startStoreDetailVC(store_id: Int) {
        
        let sb = UIStoryboard(name: "StoreDetail", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: StoreDetailViewController = sb.instantiateViewController(withIdentifier: "storedetailVC") as! StoreDetailViewController
            ms.storeId = store_id
            
            navigationController?.present(ms, animated: true)
        }
        
    }

    
    
    func startStoresList(request: Int) {
        
        let sb = UIStoryboard(name: "StoresList", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: StoresLsitViewController = sb.instantiateViewController(withIdentifier: "storeslistVC") as! StoresLsitViewController

         //   ms.request = request
            
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    func startCategoriesList() {
        
        let sb = UIStoryboard(name: "Categories", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: CategoriesViewController = sb.instantiateViewController(withIdentifier: "categoriesVC") as! CategoriesViewController
            
            ms.modalPresentationStyle = .fullScreen

            navigationController?.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
            
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    
 
    func startWalletVC() {
        
        let sb = UIStoryboard(name: "MyWallet", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            let ms: MyWalletController = sb.instantiateViewController(withIdentifier: "walletVC") as! MyWalletController
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    
    
    func startAboutVC() {
        
        let sb = UIStoryboard(name: "About", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: AboutViewController = sb.instantiateViewController(withIdentifier: "aboutVC") as! AboutViewController
    
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    
    func startSettingVC() {
        
        let sb = UIStoryboard(name: "Settings", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: SettingsViewController = sb.instantiateViewController(withIdentifier: "settingsVC") as! SettingsViewController
            
            //navigationController?.pushViewController(ms, animated: true)
        
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    
    func startNotificationListVC() {
        
        let sb = UIStoryboard(name: "Notification", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: NotificationViewController = sb.instantiateViewController(withIdentifier: "notificationVC") as! NotificationViewController
            
            navigationController?.present(ms, animated: true)
        }
        
    }
    
    
    var cloader: CategoryLoader = CategoryLoader()

    func loadCategories () {
        
        self.cloader.delegate = self
        
        //Get current Location
        
        var parameters = [
            "limit"          : "50"
        ]
        
        parameters["page"] = String(describing: 1)
       
        self.cloader.load(url: Constances.Api.API_USER_GET_CATEGORY,parameters: parameters)
    
    }
    
    
    func success(parser: CategoryParser,response: String) {
        
        if parser.success == 1 {
            
            let categories = parser.parse()
           
            if categories.count > 0 {
                categories.saveAll()
            }
        
        
        }
    }
    
    func error(error: Error?, response: String) {
        
    }
    
    
    func count_notifications(){
        
        if(!Session.isLogged()){
           // return
        }
      
        
        let api = SimpleRequestApi()
        var parameters = [
            "status": "\(0)"
        ]
        
        if(Session.isLogged()){
            if let sess = Session.getInstance(), let user = sess.user{
            
                parameters["user_id"] = "\(user.id)"
                
                if let guest = Guest.getInstance(){
                    parameters["guest_id"] = "\(guest.id)"
                }
                
                
            }
        }else if let guest = Guest.getInstance(){
            parameters["auth_type"] = "guest"
            parameters["auth_id"] = "\(guest.id)"
        }
      
        api.run(url: Constances.Api.API_GET_NOTIFICATIONS_COUNT, parameters: parameters) { (parser) in
        
            if(parser?.success == 1){
                
                Utils.printDebug("\(parser)")
                
                
                if let count = parser?.result?.intValue{
                    self.updateNotificationBadge(count: count)
                }
               
            }
            
        }
        
        
    }
    
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
  
}


extension MainViewController: SwiftWebVCDelegate {
    
    func didStartLoading() {
        print("Started loading.")
    }
    
    func didFinishLoading(success: Bool) {
        print("Finished loading. Success: \(success).")
    }
}



    
    
    
    
    
    
