//
//  GeoStoreViewController.swift
//  NearbyStores
//
//  Created by Amine on 6/30/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import GoogleMaps
import Cosmos
import RealmSwift
import MapKit
import SwiftEventBus
import GooglePlaces
import Alamofire
import SwiftyJSON
import Firebase

struct LTDestination {
    
    var delivery_boy_id: Int?
  
}



class LocationTrackerController: MyUIViewController,GMSMapViewDelegate, CLLocationManagerDelegate {
  
    var destination: LTDestination? = nil
    
    let locationManager = CLLocationManager()
    var currentLocation: CLLocationCoordinate2D? = nil


    static func newInstance() -> LocationTrackerController {
        let sb = UIStoryboard(name: "LocationTracker", bundle: nil)
        let ms: LocationTrackerController = sb.instantiateViewController(withIdentifier: "location_tracker_VC") as! LocationTrackerController
        return ms
    }

    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
        
        self.currentLocation = locValue
        
        Utils.printDebug("\(locations)")
        self.current_lat = locValue.latitude
        self.current_lng = locValue.longitude
        
       
        if let guest = Guest.getInstance(), let cl = self.currentLocation {
            
            
            let realm = try! Realm()
            try! realm.write {
                
                guest.lat = cl.latitude
                guest.lng = cl.longitude
                realm.add(guest,update: .all)
                
            }
            
            self.locationManager.stopUpdatingLocation()
            
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 15.0) {
            self.locationManager.startUpdatingLocation()
        }
        
    }
    
    
    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() {
        
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        
    }
  
    var _req_limit = 30
    

    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var viewContainer: UIView!
    
 
    
    //end
    @IBAction func zoomPlus(_ sender: Any) {
        
        if let mapView = self.mapView  {
            
            mapView.animate(toZoom: mapView.camera.zoom+1)
            
        }
        
    }
    
    @IBAction func zoomLess(_ sender: Any) {
        
        if let mapView = self.mapView  {
            
            mapView.animate(toZoom: mapView.camera.zoom-1)
 
        }
    }

    
    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 = "Map".localized
       
        navigationBarItem.titleView = topBarTitle
        
    }
   
    func setupNavBarButtons() {
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        
        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?.append(customBarButtonItem)
  
    }
    
    
    
    @objc func onBackHandler()  {
        self.dismiss(animated: true)
    }
    
    
    var mapView: GMSMapView? = nil
    
    var lastObject: Store? = nil
    @objc func onTapStoreHeader()  {
        if let object = lastObject{
           
            //show detail of store
            let sb = UIStoryboard(name: "StoreDetail", bundle: nil)
            if sb.instantiateInitialViewController() != nil {
                
                let ms: StoreDetailViewController = sb.instantiateViewController(withIdentifier: "storedetailVC") as! StoreDetailViewController
                ms.storeId = object.id
                
                self.present(ms, animated: true)
            }
        }
    }
    
    
  
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.setupViewloader()
    
        //update location
        self.locationManager.delegate = self
        self.requestLocation()
        
        
        self.navigationBar.isTranslucent = false
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        
        self.setupNavBarTitles()
        self.setupNavBarButtons()
        
        
        viewManager.showAsLoading(parent: self.view)

    
        //setup
        setupMyMarker()
        setup_delivery_marker()
        setup_firebase_database()

        
    
    }
    

    var viewManager: LoaderViewManager =  LoaderViewManager()
    
    func setupViewloader()  {
        
        //setup view loader, Error, Empty layouts
        viewManager.setup(parent: viewContainer)
    }
    
   
    
    var delivery_boy_marker: GMSMarker?
    

    func setup_maps(lat: Double, lng: Double) {
        
        let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 16)
        self.mapView = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height), camera: camera)
       
        mapView?.delegate = self
        
        if let mapView = self.mapView  {
            mapView.animate(toZoom: 16)
            viewContainer.addSubview(mapView)
        }
        
    }
    
    func setup_delivery_marker()  {
     
        guard let guest = Guest.getInstance() else{
            return
        }
        
        guard  let des = self.destination, let delivery_boy = User.findById(id: des.delivery_boy_id!) else {
            return
        }
        
        self.setup_maps(lat: delivery_boy.latitude, lng: delivery_boy.longitude)
        
       
        if let mapView = self.mapView, let des = self.destination {
            
            // Creates a marker in the center of the map.
            let marker = GMSMarker()
            marker.position = CLLocationCoordinate2D(latitude:  delivery_boy.latitude, longitude: delivery_boy.longitude)
            marker.map = mapView
        
            
            let icon = CustomViewStoreMarker()
            icon.object0 = delivery_boy
            icon.setup(marker: marker)

            marker.iconView = icon
            
            self.delivery_boy_marker = marker
            
            let camera = GMSCameraPosition.camera(withLatitude: delivery_boy.latitude, longitude: delivery_boy.longitude, zoom: 16)
            mapView.camera = camera
            mapView.animate(toZoom: mapView.camera.zoom)
            
            
        }
        
        self.viewManager.showMain()
      
    }
    
   
    
    var ref: DatabaseReference!
    
    func setup_firebase_database() {
        
        guard let sess = Session.getInstance() else{
            return
        }
     
        guard let des = self.destination, let delivery_boy = User.findById(id: des.delivery_boy_id!) else {
            return
        }
        
        
        guard let mapView = self.mapView else{
            return
        }
        
    
        ref = Database.database().reference()
        
        ref.child("users").child("user-\(delivery_boy.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){
              
                
                
                if let db_marker = self.delivery_boy_marker{
                    
                    CATransaction.begin()
                    db_marker.position =  CLLocationCoordinate2D(latitude: lat, longitude: lng)
                    CATransaction.commit()
                
                    let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 16)
                    mapView.animate(to: camera)
                    
                    Utils.printDebug("Move to \(lat) - \(lng)")
                }
                
            
                
                self.view.layoutIfNeeded()
            }else{
               
            }
            
        })
        
    
    }
    
   
    
    
    func setupMyMarker()  {
        
    
        if let guest = Guest.getInstance() {
           
            // Creates a marker in the center of the map.
            let marker = GMSMarker()
            marker.position = CLLocationCoordinate2D(latitude:  guest.lat, longitude: guest.lng)
            marker.map = mapView
            
        }
    }
   
 

    var current_lat = 0.0
    var current_lng = 0.0
    
    func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
        current_lat = position.target.latitude
        current_lng = position.target.longitude
    }
    

    var is_owner_pressed = false
    
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        
        
        
       
        return true
    }
  
 
}
