//
//  SettingsLauncher.swift
//  youtube
//
//  Created by Brian Voong on 6/17/16.
//  Copyright © 2016 letsbuildthatapp. All rights reserved.
//

import UIKit
import SwiftIcons
import AssistantKit

class Setting: NSObject {
    let name: String
    let image: UIImage
    let id: Int
    
    init(id: Int,name: String, image: UIImage) {
        self.name = name
        self.image = image
        self.id = id
    }
}


protocol SettingsLauncherDelegate {
    func onItemPressed(setting: Setting)
}

class SettingsLauncher: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    let blackView = UIView()
    
    let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        
        
    
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.clear
    
        return cv
    }()
    
    let cellId = "cellId"
    let cellHeight: CGFloat = 50
    var delegate: SettingsLauncherDelegate? = nil
   
    
    var settings: [Setting] = {
        return []
    }()
    
    var mainController: MainViewController?
    
    func load() {
        
        self.index = 0
        
        self.settings = []
    
        
        self.addBottomMenuItem(setting: Setting(
            id: MenuIDList.GEO_STORES,
            name: "Geo Stores".localized,
            image: createIcon("menu_ic_maps")
        ))
        
    
        
        if ModuleManager.isEnabled(module: "digital_wallet"){
            self.addBottomMenuItem(setting: Setting(
                id: MenuIDList.WALLET,
                name: "My wallet".localized,
                image: createIcon("ic_wallet")
            ))
        }
        
        
        if ModuleManager.isEnabled(module: "nsorder"){
            self.addBottomMenuItem(setting: Setting(
                id: MenuIDList.MY_ORDERS,
                name: "My Orders".localized,
                image: createIcon("menu_shopping_cart")
            ))
        }
        
        
        if ModuleManager.isEnabled(module: "messenger"){
            self.addBottomMenuItem(setting: Setting(
                id: MenuIDList.CHAT_LOGIN,
                name: "Inbox".localized,
                image: createIcon("menu_ic_chat")
            ))
        }
        
        self.addBottomMenuItem(setting: Setting(
            id: MenuIDList.EDIT_PROFILE,
            name: "My account".localized,
            image: createIcon("menu_ic_profile")
        ))
        
        
        self.addBottomMenuItem(setting: Setting(
            id: MenuIDList.ABOUT,
            name: "About us".localized,
            image: createIcon("menu_ic_about_us")
        ))
        
        self.addBottomMenuItem(setting: Setting(
            id: MenuIDList.SETTING,
            name: "Setting".localized,
            image: createIcon("menu_ic_setting")
        ))
        
        
        collectionView.reloadData()
        
    }
    
    var mainView: UIView = {
        return UIView()
    }()
    
  
    
    
   func showSettings() {
       //show menu
       
       if let window = UIApplication.shared.keyWindow {
           
           let bottomSpace = CGFloat(20)
           let topSpace = CGFloat(0)
          
           blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
           blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
           blackView.frame = window.frame
           blackView.alpha = 0
           blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
           
           
           let height: CGFloat = CGFloat(settings.count) * cellHeight
           let y = window.frame.height - height - bottomSpace + topSpace
       
           
           mainView = UIView(frame: CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height + (bottomSpace + topSpace) ))
          
           mainView.roundCorners(corners: [.topRight, .topLeft], radius: 20)
           
           collectionView.backgroundColor = UIColor(named: "background-color")
           mainView.backgroundColor = UIColor(named: "background-color")
           
           mainView.addSubview(collectionView)
           window.addSubview(blackView)
           window.addSubview(mainView)
           
           
          //add constraint for collection view
           collectionView.translatesAutoresizingMaskIntoConstraints = false
           collectionView.leftAnchor.constraint(equalTo: mainView.leftAnchor, constant: 0).isActive = true
           collectionView.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: 0).isActive = true
           collectionView.topAnchor.constraint(equalTo: mainView.topAnchor, constant: topSpace).isActive = true
           collectionView.bottomAnchor.constraint(equalTo: mainView.bottomAnchor, constant: bottomSpace).isActive = true
          
           
           UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
               
               self.blackView.alpha = 1
               self.mainView.frame = CGRect(x: 0, y: y, width: self.mainView.frame.width, height: self.mainView.frame.height)
               
           }, completion: nil)
       }
       
   
   }
    /*
    func showSettings() {
        //show menu
        
        if let window = UIApplication.shared.keyWindow {
            
            blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
            
            blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
            
            window.addSubview(blackView)
            
            window.addSubview(collectionView)
            
            let height: CGFloat = CGFloat(settings.count) * cellHeight
            let y = window.frame.height - height
            
            
            collectionView.roundCorners(corners: [.topRight, .topLeft], radius: 20)
            
            collectionView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height)
            
            blackView.frame = window.frame
            blackView.alpha = 0
            
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                
                self.blackView.alpha = 1
                
                self.collectionView.frame = CGRect(x: 0, y: y, width: self.collectionView.frame.width, height: self.collectionView.frame.height)
                
            }, completion: nil)
        }
    }*/
    
    /*@objc func handleDismiss(setting: Setting) {
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            
            self.blackView.alpha = 0
            
            if let window = UIApplication.shared.keyWindow {
                
                self.collectionView.frame = CGRect(x: 0, y: window.frame.height, width: self.collectionView.frame.width, height: self.collectionView.frame.height)
                
            }
            
        }) { (completed: Bool) in
            if setting.id != MenuIDList.CLOSE {
                self.mainController?.showControllerForSetting(setting: setting)
            }
        }
    }*/
    
    
    @objc func handleDismiss(setting: Setting) {
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            
            self.blackView.alpha = 0
            
            if let window = UIApplication.shared.keyWindow {
                
                self.mainView.frame = CGRect(x: 0, y: window.frame.height, width: self.mainView.frame.width, height: self.mainView.frame.height)
                
            }
            
        }) { (completed: Bool) in
            if setting.id != MenuIDList.CLOSE {
                if let del = self.delegate{
                    del.onItemPressed(setting: setting)
                }
            }
        }
    }
   
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return settings.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath) as! SettingCell
        
        let setting = settings[indexPath.item]
        cell.setting = setting
        
        return cell
    }
    
    let rowleftRightSpace = CGFloat(5)

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        
        if Device.isPhone{
            return CGSize(width: collectionView.frame.width - (rowleftRightSpace * 2),height: cellHeight)
        }else if Device.isPad{
            return CGSize(width: (collectionView.frame.width/1.5) - (rowleftRightSpace * 2),height: cellHeight)
        }else{
            
            return CGSize(width: collectionView.frame.width - (rowleftRightSpace * 2) ,height: cellHeight)
        }
        
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let setting = self.settings[indexPath.item]
        handleDismiss(setting: setting)
    }
    
    override init() {
        super.init()
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        collectionView.register(SettingCell.self, forCellWithReuseIdentifier: cellId)
        
        
       
        load()
       
        
       
        
        
    }
    
    
    
    var index = 0
    func addBottomMenuItem(setting: Setting)  {
        
        if AppConfig.Menu.list[setting.id] == true {
            self.settings.insert(setting, at: index)
            index += 1
        }
        
    }
    
    func createIcon(_ icon: FontType) -> UIImage {
        return UIImage.init(icon: icon, size: CGSize(width: 25, height: 25), textColor: UIColor.darkGray)
    }
    
    func createIcon(_ named: String) -> UIImage {
        let icon = UIImage(named: named)
        return icon!.withRenderingMode(.alwaysTemplate)
    }
    

    
}

struct MenuIDList {
    static let CATEGORIES = 1
    static let GEO_STORES = 2
    static let MY_ORDERS = 12
    static let CHAT_LOGIN = 3
    static let MY_ACCOUNT = 312
    static let PEOPLE_AROUND_ME = 4
    static let FAVOURITES = 5
    static let MY_EVENTS = 6
    static let EDIT_PROFILE = 7
    static let LOGOUT = 8
    static let MANAGE_STORES = 9
    static let SETTING = 10
    static let ABOUT = 11
    static let CLOSE = -1
    static let WALLET = 143
    
}







