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

import UIKit
import Atributika
import AssistantKit
import SwiftyJSON
import MapKit
import RealmSwift
import SwiftEventBus
import FirebaseDatabase


struct OrderDeliveryStatus {
    static let ALL = -1
    static let PENDING = 0
    static let ONGOING = 1
    static let PICKED_UP = 2
    static let DELIVERED = 3
    static let REPORTED = 4
}

class OrderDetailViewController: MyUIViewController, EmptyLayoutDelegate, ErrorLayoutDelegate{
    
    
    
    var order: Order? = nil
    var cf_lat: Double?
    var cf_lng: Double?
    var cf_fullname: String?
    var cf_address: String?
    var cf_phone1: String?
    //var cf_phone2: String?

    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var stackview: UIStackView!

    
    @IBOutlet weak var order_button_container: UIView!
    @IBOutlet weak var order_update_btn: UIButton!
    
   
    @IBAction func update_order_action(_ sender: Any) {
        
        
        let vc = LocationTrackerController.newInstance()
        
        if let order = self.order{
            
            guard let store = Store.findById(id: order.store_id) else {
                return
            }
            
            guard let delivery_boy = User.findById(id: order.delivery_id) else {
                return
            }
            
            guard let sess = Session.getInstance(), let delivery_user = sess.user else {
                return
            }
            
            
            var destination = LTDestination()
            destination.delivery_boy_id = delivery_boy.id
            
          
            vc.destination = destination
           
        }

        self.present(vc, animated: true)
        
        
    }
    
    func onReported() {
        
        
        guard let order = self.order else {
            return
        }
        
        let realm = try! Realm()
        realm.beginWrite()
        order.delivery_status = OrderDeliveryStatus.REPORTED
        try! realm.commitWrite()
        
      
        order.save()
    
        self.stackview.removeAllArrangedSubviews()
        
        self.load_store()
    

        //refresh list if needed
        SwiftEventBus.post("on_refresh", sender: true)
        
    }
   
    
    func startReportVC(order: Order) {
        
       /* let sb = UIStoryboard(name: "ReportController", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: ReportController = sb.instantiateViewController(withIdentifier: "report_vc") as! ReportController
            
            ms.order = order
            ms.delegate = self
            
            self.present(ms, animated: true)
        }
        
 */
    }
    
    func setupOrderButtons(){
    
        self.order_update_btn.setTitle("Track your order".localized, for: .normal)
        self.order_update_btn.initBoldFont()
        self.order_update_btn.setTitleColor(.white, for: .normal)
        
        self.order_update_btn.backgroundColor = Colors.primaryColor
        self.order_button_container.backgroundColor = Colors.primaryColor
        self.order_button_container.isHidden = true
        
    }
    
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        
        return titleLabel
        
    }()
    
    func setupNavBarTitles() {
        
        
        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 = "Order #\(order!.id)".localized
        
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    
    
    func setupNavBarButtons() {
        
        let color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        
        //arrow back icon
        var arrowImage: UIImage? = nil
        if Utils.isRTL(){
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: color)
        }else{
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: color)
        }
        
        
        let customBarButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
        customBarButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: color)
        
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
        
    }
    
    @objc func onBackHandler()  {
        self.dismiss(animated: true)
    }
    
    var viewManager: LoaderViewManager =  LoaderViewManager()
    
    func setupViewloader()  {
        
        //setup view loader, Error, Empty layouts
        viewManager.setup(parent: self.view)
        viewManager.getEmptyLayout().delegate = self
        viewManager.getErrorLayout().delegate = self
       
    }
    
    var ref: DatabaseReference!
    
    func setup_firebase_database() {
    
        ref = Database.database().reference()
        
        if let sess = Session.getInstance(), let user = sess.user, let ordrr = self.order{
          
            if ordrr.delivery_status != OrderDeliveryStatus.PICKED_UP{
                return
            }
            
            ref.child("users").child("user-\(ordrr.delivery_id)").observe(DataEventType.value, with: { (snapshot) in
                
                let value = snapshot.value as? NSDictionary
             
                let lat = value?["lat"] as? Double ?? 0
                let lng = value?["lng"] as? Double ?? 0
            
                if(lat != 0 && lng != 0){
                    
                    guard let delivery_boy = User.findById(id: ordrr.delivery_id) else {
                        return
                    }
                    
                    let realm = try! Realm()
                    realm.beginWrite()
                    delivery_boy.latitude = lat
                    delivery_boy.longitude = lng
                    try! realm.commitWrite()
                    
                    delivery_boy.save()
                    
                    self.order_button_container.isHidden = false
                   
                }else{
                    self.order_button_container.isHidden = true
                }
                
            })
            
        }
        
    
    }
    
    
    override func viewDidLoad() {
        
        setupNavBarTitles()
        setupNavBarButtons()
        
        
        load_store()
    
        
        setupOrderButtons()
        
    }
    
    func setupAll()  {
        
        setupViewOrderHeader()
        setupViewOrderItems()
        //setupLocateAll()
        setupViewTimeline()
        setup_firebase_database()
        
    
    }
    
    func onReloadAction(action: EmptyLayout) {
        
    }
    
    func onReloadAction(action: ErrorLayout) {
        
        
    }
    
    func setupViewOrderHeader() {
        
        //Order Detail Header
        let title :TextLine = UINib(nibName: "TextLine", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! TextLine
        title.header(title: "Order Detail".localized)
        self.stackview.addArrangedSubview(title)
        title.heightAnchor.constraint(equalToConstant: 40).isActive = true
           

        let order_id = UIStackView.col2_labelView(text: "Order ID".localized , value: "#\(order!.id)")
        
        self.stackview.addArrangedSubview(order_id)
        order_id.heightAnchor.constraint(equalToConstant: 30).isActive = true
       
    
        let order_date = UIStackView.col2_labelView(text: "Order Date".localized , value: DateUtils.UTCToLocal(date: order!.created_at, fromFormat: DateFomats.defaultFormatTimeUTC, toFormat: DateFomats.defaultFormatDate1))
        
        self.stackview.addArrangedSubview(order_date)
        order_date.heightAnchor.constraint(equalToConstant: 30).isActive = true
        
        //payment status
        let payment_status_text = order!.payment_status.split(separator: ";")
        

        if(payment_status_text.count > 0){
            
            let s:String  = String(payment_status_text[0])
            let c:String  = String(payment_status_text[1])
          
            let payment = UIStackView.col2_labelView(text: "Payment".localized , value: s)
        
            self.stackview.addArrangedSubview(payment)
            payment.heightAnchor.constraint(equalToConstant: 30).isActive = true
            
            payment.isHidden = false
            
        }
       
        
        
    }
    
    
    func setupViewOrderItems() {
        
        //Order Detail Header
        let title = TextLine.newInstance()
        title.header(title: "Order Item(s)".localized)
        self.stackview.addArrangedSubview(title)
        title.heightAnchor.constraint(equalToConstant: 40).isActive = true
       
        
        var total = 0.0
        var total_currency: Currency? = nil
        
        
        for item in order!.items{
            
            var price = ""
            if let currency = item.currency {
                if let pprice = currency.parseCurrencyFormat(price: Float(item.amount * item.Qty)){
                    price = pprice
                    total_currency = currency
                }
            }
            
            
            total = ( item.amount * item.Qty ) + total
          
          
            let item1 = UIStackView.col2_labelView(text: item.name+" x \(Int(item.Qty))", value: String( price ))
            item1.spacing = 10
            
            self.stackview.addArrangedSubview(item1)
            
            
        }
        
    
        
        let space0  =  TextLine.newInstance()
        space0.line.isHidden = true
        space0.backgroundColor = .clear
        self.stackview.addArrangedSubview(space0)
        space0.heightAnchor.constraint(equalToConstant: 10).isActive = true
        
        
        if let currency = total_currency {
            if order!.discountsValue > 0 || order!.discountsValue < 0{
                var roundedF = Float(String(format: "%.2f", (order?.discountsValue)!))
                if let discount_amount = currency.parseCurrencyFormat(price: Float( order!.discountsValue )){
                    
                    let discountLabel = UIStackView.col2_labelView(text: "Discounts".localized, value: discount_amount) { label1, label2 in
                        label2.textColor = UIColor.red
                    }
                    
                    self.stackview.addArrangedSubview(discountLabel)
                }
            }
        }
        
        
        if let currency = total_currency {
            
            if order!.amount > 0 {
                
                if let pprice = currency.parseCurrencyFormat(price: Float(order!.amount)){
                               
                    let extras = OrderParser.parse_extras(order: order!)
                    var extras_value = 0.0
                    
                    if extras.count > 0{
                        for (key, value) in extras {
                            extras_value = value + extras_value
                        }
                    }
                    
                    let taxes_value = order?.taxesValue
                    var roundedF = Float(String(format: "%.2f", taxes_value!))
                    
                    if let tax_amount = currency.parseCurrencyFormat(price: Float( taxes_value! )), roundedF! > 0{
                        
                        let tax = UIStackView.col2_labelView(text: "Taxes".localized, value: tax_amount)
                        self.stackview.addArrangedSubview(tax)
                        
                    }
                    
                    
                    if extras.count > 0{
                        for (key, value) in extras {
                            
                            if let pprice = currency.parseCurrencyFormat(price: Float(value)){
                                let total = UIStackView.col2_labelView(text: key.localized, value: "\(pprice)")
                                self.stackview.addArrangedSubview(total)
                
                            }
                          
                        }
                    }
                    
                    
                    let space001 = TextLine.newInstance()
                    self.stackview.addArrangedSubview(space001)
                    space001.heightAnchor.constraint(equalToConstant: 10).isActive = true
                 
                    let total = UIStackView.col2_labelView(text: "TOTAL".localized, value: pprice) { label1, label2 in
                        label1.initBolodFont()
                        label2.initBolodFont()
                    }
                    
                    self.stackview.addArrangedSubview(total)
                    
                    
                }
            }else if let pprice = currency.parseCurrencyFormat(price: Float(total)){
                               
                let total = UIStackView.col2_labelView(text: "Total".localized, value: pprice) { label1, label2 in
                    label1.initBolodFont()
                    label2.initBolodFont()
                }
                   self.stackview.addArrangedSubview(total)
                  // total.heightAnchor.constraint(equalToConstant: 30).isActive = true
   
            }
            
        }
        
        
        let space  =  TextLine.newInstance()
        self.stackview.addArrangedSubview(space)
        space.heightAnchor.constraint(equalToConstant: 10).isActive = true
      
    }
 
 

    
    func setupViewTimeline() {
        
        guard let order = self.order else {
            return
        }
        
        //Order Detail Header
        let title  =  TextLine.newInstance()
        self.stackview.addArrangedSubview(title.header(title: "Order status".localized))
        title.heightAnchor.constraint(equalToConstant: 40).isActive = true
        
        if(ModuleManager.isEnabled(module: "delievry")){
            
            var sv: UIStackView? = nil

           
            if(order.delivery_status == 0){
                
                sv = UIStackView.col2_labelView(text: "Delievery Status".localized, value: "Pending".localized, color: .orange)
                
               
            }else if(order.delivery_status == 1){
               
                sv = UIStackView.col2_labelView(text: "Delievery Status".localized, value: "Ongoing".localized, color: .blue)
                
                
            }else if(order.delivery_status == 2){
               
                sv = UIStackView.col2_labelView(text: "Delievery Status".localized, value: "Picked Up".localized, color: .blue)
                
                
            }else if(order.delivery_status == 3){
              
                
                sv = UIStackView.col2_labelView(text: "Delievery Status".localized, value: "Delivered".localized, color: Colors.lightGreen)
                
            }else if(order.delivery_status == 4){
              
                sv = UIStackView.col2_labelView(text: "Delievery Status".localized, value: "Reported".localized, color: .red)
                
            }
        
            if let v = sv{
                self.stackview.addArrangedSubview(v)
                v.heightAnchor.constraint(equalToConstant: 30).isActive = true
            }
            
        }
        
        
        if(order.timeline.count == 0){
            let status = UILabel.new(label_text: "Pending".localized)
            status.textColor = .orange
            self.stackview.addArrangedSubview(status)
            status.heightAnchor.constraint(equalToConstant: 30).isActive = true
            return
        }
        
          Utils.printDebug("\(order.timeline)")
          
          var frames: [TimeFrame] = []
          
          var index = 0
          for point in order.timeline {
          
              var message = "\(point.date) - \(point.message)"
              let date = DateUtils.UTCToLocal(date: point.date, fromFormat: DateFomats.defaultFormatTimeUTC, toFormat: DateFomats.defaultFormatTime)
              
              if point.message != ""{
                  message = "\(date) - \(point.message)"
              }else{
                  message = "\(date)"
              }
              
              
              Utils.printDebug("\(point.id)")
              
              if Int(point.id) == 4{
                  
                  var icon: UIImage?
                  
                  if(index ==  (order.timeline.count - 1)){
                    
                      icon = UIImage.init(icon: .googleMaterialDesign(.motorcycle), size: CGSize(width: 22, height: 22), textColor: Colors.primaryColor)
                  }else{
                      icon =  UIImage(named: "check")
                  }
                   
                  frames.append(
                      TimeFrame(title: point.status.capitalizingFirstLetter(), text: message, image: icon)
                  )
                  
              }else{
                  
                  frames.append(
                      TimeFrame(title: point.status.capitalizingFirstLetter(), text: message, image: UIImage(named: "check"))
                  )
                  
              }
            
            
                if(index ==  (order.timeline.count - 1)) && Int(point.id) != 4{
                    frames.append(
                        TimeFrame(title: "", text: "", image: nil)
                    )
                }
              
              
              index = index + 1
          }
          
          let timeline = TimelineView(bulletType: .circle, timeFrames: frames)
          self.stackview.addArrangedSubview(timeline)
          timeline.lineColor = Colors.green
         
       
        
        
        let space3  =  TextLine.newInstance()
        space3.line.isHidden = true
        self.stackview.addArrangedSubview(space3)
        space3.heightAnchor.constraint(equalToConstant: 10).isActive = true

       
    }
    
   
}


extension OrderDetailViewController: StoreLoaderDelegate, UserLoaderDelegate {


    //load store
 
    func load_store () {
        
        
        viewManager.showAsLoading(parent: self.view)
        
        var storeLoader: StoreLoader = StoreLoader()
        storeLoader.delegate = self
        
        //Get current Location
        
        var parameters = [
            "limit"          : "1"
        ]
        
        if let guest = Guest.getInstance() {
            
            parameters["latitude"] = String(guest.lat)
            parameters["longitude"] = String(guest.lng)
            
            if let orde = self.order{
                parameters["store_id"] = String(order!.store_id)
            }
           
        }
        
        Utils.printDebug("\(parameters)")
        
        storeLoader.load(url: Constances.Api.API_USER_GET_STORES,parameters: parameters)
  
    }
    
    func success(parser: StoreParser,response: String) {
    
        MyProgress.dismiss()
        
        if parser.success == 1 {

            let stores = parser.parse()
           
            if stores.count > 0 {
                
                stores[0].save()
                
                if let order = self.order, order.delivery_id == 0{
                    setupAll()
                }else{
                    load_user()
                }
               
                
            }
            
        }else {
          
            
        }
        
    }
    
    
    //load store
   
    func load_user () {
        
        
        viewManager.showAsLoading(parent: self.view)
        
        let userLoader: UserLoader = UserLoader()
    
        userLoader.delegate = self
        
        //Get current Location
        
        var parameters = [
            "limit"          : "1"
        ]
        

        
        if let orde = self.order{
            parameters["uid"] = String(order!.delivery_id)
        }
        
        Utils.printDebug("parameters: \(parameters)")
        
        userLoader.load(url: Constances.Api.API_GET_USERS,parameters: parameters)
        
    }
    
    func success(parser: UserParser,response: String) {
        

        MyProgress.dismiss()
        
        Utils.printDebug("response: \(response)")
        
        if parser.success == 1 {
            
            let users = parser.parse()
            
            if users.count > 0 {
                
                users[0].save()
                
                setupAll()
                viewManager.showMain()
             
                
            }else{
                viewManager.showAsEmpty()
            }
            
        }else {
            
            if parser.errors != nil {
                viewManager.showAsError()
            }
            
        }
        
    }
    
    func error(error: Error?, response: String) {
        
    }
    
    
    func parseCFData(content: String) -> JSON? {
        
        if let dataFromString = content.data(using: .utf8, allowLossyConversion: false) {
         
             do {
                 return try JSON(data: dataFromString)
             } catch {
                 Utils.printDebug("json content not valid! => \(content)")
                 return nil
             }
         
         }
        
        return nil
    }
    
    func getLocationFromJSON(content: String) -> CLLocationCoordinate2D  {
        
        let arr = content.split{$0 == ";"}.map(String.init)
        
        var d = CLLocationCoordinate2D()
        d.latitude = Double(arr[1])!
        d.longitude = Double(arr[2])!
        
        return d
    }
    
}

