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

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



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
    static let PAID = 5
}

class OrderDetailViewController: MyUIViewController, EmptyLayoutDelegate, ErrorLayoutDelegate, ContactPopupDelegate, ReportDelegate{
    
    
    
    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) {
        
        
        
        guard let order = self.order else {
            return
        }
        guard let sess = Session.getInstance(), let user = sess.user else {
            return
        }
    

        let alert = UIAlertController(title: "Delivery Status".localized, message: nil, preferredStyle: .actionSheet)
        
        
        if self.order?.delivery_status == 1{ //ongoing
            alert.addAction(UIAlertAction(title: "Picked up".localized, style: .default) { _ in
                //call api
                
                //make it as ongoing
                let parameters = [
                    "order_id": order.id,
                    "status": OrderDeliveryStatus.PICKED_UP,
                    "delivery_id": user.id,
                ]
                
                self.viewManager.showAsLoading()
              
                let api = SimpleRequestApi()
                api.run(url: OrderConstances.Api.API_DELIVERY_UPDATE_STATUS, parameters: parameters) { (parser) in
                
                    if parser?.success == 1{
                    
                        
                        let realm = try! Realm()
                        realm.beginWrite()
                        order.delivery_status = OrderDeliveryStatus.PICKED_UP
                        try! realm.commitWrite()
                       
                        order.save()
                    
                        self.stackview.removeAllArrangedSubviews()
                        
                        self.load_store()
                        
                        
                        //refresh list if needed
                        SwiftEventBus.post("on_refresh", sender: true)
                        
                    }
                    
                 
                }
                
            })
        }
       
        
        if self.order?.delivery_status == 2{ //picked up
            
            alert.addAction(UIAlertAction(title: "Delivered".localized, style: .default) { _ in
                //call api
                
                //make it as ongoing
                let parameters = [
                    "order_id": order.id,
                    "status": OrderDeliveryStatus.DELIVERED,
                    "delivery_id": user.id,
                ]
                
                self.viewManager.showAsLoading()
              
                let api = SimpleRequestApi()
                api.run(url: OrderConstances.Api.API_DELIVERY_UPDATE_STATUS, parameters: parameters) { (parser) in
                
                    if parser?.success == 1{
                        
                        let realm = try! Realm()
                        realm.beginWrite()
                        order.delivery_status = OrderDeliveryStatus.DELIVERED
                        try! realm.commitWrite()
                       
                        order.save()
                    
                        self.stackview.removeAllArrangedSubviews()
                        
                        self.load_store()
                        
                        //refresh list if needed
                        SwiftEventBus.post("on_refresh", sender: true)
                        
                        
                    }
                    
                 
                }
            })
        }
        
        
        alert.addAction(UIAlertAction(title: "Report".localized, style: .default) { _ in
            
            self.startReportVC(order: order)
            
        })
        
        
        
        alert.addAction(UIAlertAction(title: "Cancel".localized, style: .default) { _ in
            alert.dismiss(animated: true)
        })
        
        self.present(alert, animated: true, completion: nil)
        
    }
    
    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("Update".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
       
    }
    
    override func viewDidLoad() {
        
        setupNavBarTitles()
        setupNavBarButtons()
        
        
        load_store()
      
        
        setupOrderButtons()
        
    }
    
    func setupAll()  {
        
        setupViewOrderHeader()
        setupViewOrderItems()
        setupViewPickupFrom()
        setupViewDeliverTo()
        //setupLocateAll()
        setupViewTimeline()
    
        if order?.delivery_status == OrderDeliveryStatus.PENDING {
            order_button_container.isHidden = true
        }else{
            order_button_container.isHidden = false
        }
    
        self.view.layoutIfNeeded()
    
    }
    
    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!.amount > 0 {
                
                if let pprice = currency.parseCurrencyFormat(price: Float(order!.amount)){
                    let total = UIStackView.col2_labelView(text: "Total".localized, value: pprice)
                    self.stackview.addArrangedSubview(total)
                }
                
            }else if let pprice = currency.parseCurrencyFormat(price: Float(total)){
                               
                let total = UIStackView.col2_labelView(text: "Total".localized, value: pprice)
                   self.stackview.addArrangedSubview(total)
                   total.heightAnchor.constraint(equalToConstant: 30).isActive = true
   
            }
            
            
            if(order!.delivery_status == OrderDeliveryStatus.DELIVERED){
                if let value = currency.parseCurrencyFormat(price: Float( order!.delivery_commission )){
                    let deliveryValue = UIStackView.col2_labelView(text: "You got".localized, value: "\(value)")
                    
                    (deliveryValue.arrangedSubviews[1] as? UILabel)?.initBolodFont()
                    (deliveryValue.arrangedSubviews[1] as? UILabel)?.textColor = Colors.green
                   
                    stackview.addArrangedSubview(deliveryValue)
                }
            }else{
                if let value = currency.parseCurrencyFormat(price: Float( order!.delivery_commission )){
                    let deliveryValue = UIStackView.col2_labelView(text: "You get".localized, value: "+\(value)")
                    
                    (deliveryValue.arrangedSubviews[1] as? UILabel)?.initBolodFont()
                    (deliveryValue.arrangedSubviews[1] as? UILabel)?.textColor = Colors.green
                   
                    
                    stackview.addArrangedSubview(deliveryValue)
                }
            }
            
            
        }
        
        
        let space  =  TextLine.newInstance()
        self.stackview.addArrangedSubview(space)
        space.heightAnchor.constraint(equalToConstant: 10).isActive = true
      
    }
    
    lazy var contactPopup: ContactPopupView = {
          let launcher = ContactPopupView()
          return launcher
      }()
    
    var selected_object_store: Store?
    var selected_object_client: User?
    
    func setupViewPickupFrom() {
        
        guard let store = Store.findById(id: order!.store_id) else {
            return
        }
        
        
        //Order Detail Header
        let title  =  TextLine.newInstance()
        self.stackview.addArrangedSubview(title.header(title: "Pickup from".localized))
        title.heightAnchor.constraint(equalToConstant: 40).isActive = true
      
        
        let fullname = UILabel.newKV(label_text: "Store".localized, label_value: store.name)
        self.stackview.addArrangedSubview(fullname)
        fullname.heightAnchor.constraint(equalToConstant: 30).isActive = true
       
        
        let address = UILabel.newKV(label_text: "Address".localized, label_value: store.address)
        self.stackview.addArrangedSubview(address)
        address.heightAnchor.constraint(equalToConstant: 40).isActive = true
       
        
        let space1  =  TextLine.newInstance()
        space1.line.isHidden = true
        self.stackview.addArrangedSubview(space1)
        space1.heightAnchor.constraint(equalToConstant: 10).isActive = true
        
        
        let buttons = UserContact2Cols()
        buttons.setup(b1: "Contact".localized, b2: "Location".localized) { (contactBtn) in
            
            
            self.contactPopup.show(id: 9999999)
            self.contactPopup.delegate = self
            
            self.contactPopup.mView?.left_contact_btn.setTitle("Call".localized, for: .normal)
            self.contactPopup.mView?.right_contact_btn.setTitle("Chat".localized, for: .normal)
            
            
            self.selected_object_store = store
            self.selected_object_client = nil
            
        } compilationB2: { (locationBtn) in
            
            let vc = LocationTrackerController.newInstance()
            
            if let order = self.order{
                
                guard let store = Store.findById(id: order.store_id) else {
                    return
                }
                
                guard let client = User.findById(id: order.user_id) else {
                    return
                }
                
                guard let sess = Session.getInstance(), let delivery_user = sess.user else {
                    return
                }
                
                
                var destination = LTDestination()
                destination.pickup_from = store.id
                destination.order = self.order
                
                var position = CLLocationCoordinate2D()
                position.latitude = store.latitude
                position.longitude = store.longitude
                
                vc.selected_target_position = position
                vc.selected_target_name = store.name
                
                vc.destination = destination
               
            }
    
            self.present(vc, animated: true)
            
        }

        self.stackview.addArrangedSubview(buttons)
        buttons.heightAnchor.constraint(equalToConstant: 40).isActive = true
        
       // buttons.btn2!.isHidden = true
        buttons.btn1!.setCustomButtonControlStyle(active: false)
        buttons.btn2!.setCustomButtonControlStyle(active: false)
        
      
        let space2  =  TextLine.newInstance()
        space2.line.isHidden = true
        self.stackview.addArrangedSubview(space2)
        space2.heightAnchor.constraint(equalToConstant: 10).isActive = true
      
       
    }
    
    
    func onLeftPressed(id: Int) {
        
        if let object = self.selected_object_client{
            
            var phone = ""
            
            if let p = self.cf_phone1{
                phone = p
            }
            
            
            phone = phone.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
            let result = phone.isValid(regex: .phone)
            
            if result{
                
                if let url = URL(string: "tel://\(phone)"), UIApplication.shared.canOpenURL(url) {
                    if #available(iOS 10, *) {
                        UIApplication.shared.open(url)
                    } else {
                        UIApplication.shared.openURL(url)
                    }
                }else{
                    
                    let message: [String:String] = ["alert":"This app is not allowed to query for scheme tel".localized]
                    self.showAlertError(title: "Alert!".localized, content: message, msgBnt: "OK".localized)
                    
                }
                
            }else{
                
                let message: [String:String] = ["alert":"This app is not allowed to query for scheme tel or Phone number is not valid".localized]
                self.showAlertError(title: "Alert!".localized, content: message, msgBnt: "OK".localized)
                
            }
            
        }else if let object = self.selected_object_store{
            
            let phone = object.phone.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
            let result = phone.isValid(regex: .phone)
            
            if result{
                
                if let url = URL(string: "tel://\(phone)"), UIApplication.shared.canOpenURL(url) {
                    if #available(iOS 10, *) {
                        UIApplication.shared.open(url)
                    } else {
                        UIApplication.shared.openURL(url)
                    }
                    
                    
                }else{
                    
                    let message: [String:String] = ["alert":"This app is not allowed to query for scheme tel".localized]
                    self.showAlertError(title: "Alert!".localized, content: message, msgBnt: "OK".localized)
                    
                }
                
            }else{
                
                let message: [String:String] = ["alert":"This app is not allowed to query for scheme tel or Phone number is not valid".localized]
                self.showAlertError(title: "Alert!".localized, content: message, msgBnt: "OK".localized)
                
            }
            
        }
        
    }
    
    func onRightPressed(id: Int) {
        
        if let object = self.selected_object_client{
            
            //chat with store.id
             
            let sb = UIStoryboard(name: "Messenger", bundle: nil)
            if sb.instantiateInitialViewController() != nil {
                
                let ms: MessengerViewController = sb.instantiateViewController(withIdentifier: "messengerVC") as! MessengerViewController
                ms.client_id = object.id
                self.present(ms, animated: true)
                
            }
            
        }else if let object = self.selected_object_store{
            
            let sb = UIStoryboard(name: "Messenger", bundle: nil)
            if sb.instantiateInitialViewController() != nil {
                
                let ms: MessengerViewController = sb.instantiateViewController(withIdentifier: "messengerVC") as! MessengerViewController
                ms.client_id = object.user_id
                self.present(ms, animated: true)
            }
            
        }
        
    }
    
    
    
    func setupViewDeliverTo() {
        
        guard let client = User.findById(id: order!.user_id) else {
            return
        }
        
        var fullname_text = client.name
        var address_text = ""
       
        
        if let cf_address = self.cf_address{
            address_text = cf_address
        }
        
        if let cf_fullname = self.cf_fullname{
            fullname_text = cf_fullname
        }
        
        
        //Order Detail Header
        let title  =  TextLine.newInstance()
        self.stackview.addArrangedSubview(title.header(title: "Delivery to".localized))
        title.heightAnchor.constraint(equalToConstant: 40).isActive = true
      
        
        let fullname = UILabel.newKV(label_text: "Client".localized, label_value: fullname_text)
        self.stackview.addArrangedSubview(fullname)
        fullname.heightAnchor.constraint(equalToConstant: 30).isActive = true
       
        
        let address = UILabel.newKV(label_text: "Address".localized, label_value: address_text)
        self.stackview.addArrangedSubview(address)
        address.heightAnchor.constraint(equalToConstant: 40).isActive = true
       
        
        let space1  =  TextLine.newInstance()
        space1.line.isHidden = true
        self.stackview.addArrangedSubview(space1)
        space1.heightAnchor.constraint(equalToConstant: 10).isActive = true
        
        
    
       let buttons = UserContact2Cols()
        buttons.setup(b1: "Contact".localized, b2: "Location".localized) { (contactBtn) in
            
            self.contactPopup.show(id: 99)
            self.contactPopup.delegate = self
            
            self.contactPopup.mView?.left_contact_btn.setTitle("Call".localized, for: .normal)
            self.contactPopup.mView?.right_contact_btn.setTitle("Chat".localized, for: .normal)
            
            self.selected_object_store = nil
            self.selected_object_client = client
            
        } compilationB2: { (locationBtn) in
            
            let vc = LocationTrackerController.newInstance()
            
            if let order = self.order{
                
                guard Store.findById(id: order.store_id) != nil else {
                    return
                }
                
                guard User.findById(id: order.user_id) != nil else {
                    return
                }
                
                guard let sess = Session.getInstance(), let _ = sess.user else {
                    return
                }
                
                var destination = LTDestination()
                destination.delivery_to = order.user_id
                
                if let cf_address = self.cf_address{
                    destination.cf_address = cf_address
                }
                
                if let cf_lat = self.cf_lat{
                    destination.cf_lat = cf_lat
                }
                
                if let cf_lng = self.cf_lng{
                    destination.cf_lng = cf_lng
                }
                
                destination.order = self.order
                
                if let cf_lat = self.cf_lat, let cf_lng = self.cf_lng, let cf_address = self.cf_address{
                    
                    var position = CLLocationCoordinate2D()
                    position.latitude = cf_lat
                    position.longitude = cf_lng
                    
                    vc.selected_target_position = position
                    vc.selected_target_name = cf_address
                    
                }
               
                vc.destination = destination
                
            }
    
            self.present(vc, animated: true)
            
        }

        self.stackview.addArrangedSubview(buttons)
        buttons.heightAnchor.constraint(equalToConstant: 40).isActive = true
        
        buttons.btn1!.setCustomButtonControlStyle(active: false)
        buttons.btn2!.setCustomButtonControlStyle(active: false)
    
        let space2  =  TextLine.newInstance()
        space2.line.isHidden = true
        self.stackview.addArrangedSubview(space2)
        space2.heightAnchor.constraint(equalToConstant: 10).isActive = true
      
       
        
        order_button_container.isHidden = false
    }
    
    
    func setupLocateAll() {
        
        
        let buttons = UserContact2Cols()
        buttons.setup(b1: "Locate All".localized, b2: "Location".localized) { (contactBtn) in
            
            let vc = LocationTrackerController.newInstance()
            
            if let order = self.order{
                
                guard Store.findById(id: order.store_id) != nil else {
                    return
                }
                
                guard User.findById(id: order.user_id) != nil else {
                    return
                }
                
                guard let sess = Session.getInstance(), let _ = sess.user else {
                    return
                }
                
                var destination = LTDestination()
                destination.delivery_to = order.user_id
               
                
                if let cf_address = self.cf_address{
                    destination.cf_address = cf_address
                }
                
                if let cf_lat = self.cf_lat{
                    destination.cf_lat = cf_lat
                }
                
                if let cf_lng = self.cf_lng{
                    destination.cf_lng = cf_lng
                }
                
                
                destination.pickup_from = order.store_id
               
                vc.destination = destination
                
            }
    
            self.present(vc, animated: true)
            
            
        } compilationB2: { (locationBtn) in
            
            
        }
        
        buttons.btn2?.isHidden = true
        
        self.stackview.addArrangedSubview(buttons)
        buttons.heightAnchor.constraint(equalToConstant: 40).isActive = true
        
        
        buttons.btn1!.setCustomButtonControlStyle(active: true)
        buttons.btn2!.setCustomButtonControlStyle(active: true)
      
        
        let space2  =  TextLine.newInstance()
        space2.line.isHidden = true
        self.stackview.addArrangedSubview(space2)
        space2.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: "Status".localized))
        title.heightAnchor.constraint(equalToConstant: 40).isActive = true
        
        
      
       
        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
        }
    
       
      
        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"))
                )
                
            }
            
            
            
            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) {
    
        if parser.success == 1 {

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

        
        if let orde = self.order{
            parameters["uid"] = String(order!.user_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 {
               
                //get client location
                guard  let cfjson = order?.CFData else {
                   return
                }
               
              
                do {
              
                    let json = Parser(array: cfjson)
                
                    let address = json.result!["Delivery to"].stringValue
                    let address_arr = address.components(separatedBy: ";")
                    
                    guard address_arr.count > 1 else {
                        self.showAlertError(title: "Alert".localized, content: ["err":"Address doesn't valid!".localized], msgBnt: "OK".localized)
                       return
                    }
                  
                    Utils.printDebug("\(cfjson)")
                    
                    self.cf_address = address_arr[0]
                    
                    self.cf_lat = Double(address_arr[1])
                    self.cf_lng = Double(address_arr[2])
                    self.cf_phone1 = json.result!["Phone"].stringValue
                    self.cf_fullname = json.result!["Full name"].stringValue
                    
                   
                } catch {
                    
                }
                
                
                users[0].save()
                
            
                setupAll()
                viewManager.showResult()
             
                
            }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
    }
    
}

