//
//  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

protocol LocationPickerDelegate {
    func onFinished(lat: Double, lng: Double, address: String)
}

class LocationPickerViewController: MyUIViewController,GMSMapViewDelegate, CLLocationManagerDelegate {
    
    
    var delegate: LocationPickerDelegate?
    
    
    let locationManager = CLLocationManager()
    var currentLocation: CLLocationCoordinate2D? = nil


    var picked_lat: Double?
    var picked_lng: Double?
    var picked_address: String?
    
    
    static func newInstance() -> LocationPickerViewController {
        let sb = UIStoryboard(name: "LocationPicker", bundle: nil)
        let ms: LocationPickerViewController = sb.instantiateViewController(withIdentifier: "location_picker_VC") as! LocationPickerViewController
        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 latitude: Double? = nil
    var longitude: Double? = nil
    var name: String? = nil
    
    var _req_limit = 30
    
    
    @IBOutlet weak var save_btn_container: UIView!
    @IBOutlet weak var save_location_btn: UIButton!
    
    
    @IBOutlet weak var marker_home_icon: UIImageView!
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var viewContainer: UIView!
    
    @IBAction func save_location_Action(_ sender: Any) {
   
        if picked_address == nil{
            picked_address = ""
        }
        
        if let del = delegate{
           del.onFinished(lat: current_lat, lng: current_lng, address: picked_address!)
        }
        
        self.dismiss(animated: true)
        
    }
    
    //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
        
        if let name = self.name, let _ = self.latitude {
             topBarTitle.text = name
        }else{
             topBarTitle.text = "Location Picker".localized
        }
       
        navigationBarItem.titleView = topBarTitle
        
    }
   
    func setupNavBarButtons() {
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
            
        
        let color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
     
    
        //setp search icon btn
        let searchIcon = UIImage.init(icon: .linearIcons(.magnifier), size: CGSize(width: 25, height: 25), textColor: color)
        let searchBarButtonItem = UIBarButtonItem(image: searchIcon, style: .plain, target: self, action: #selector(handleSearch))
        searchBarButtonItem.setIcon(icon: .linearIcons(.magnifier), iconSize: 25, color: color)
        
        navigationBarItem.rightBarButtonItems?.append(searchBarButtonItem)
        
        
       
        //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 handleSearch() {
        
        startAutocompleteController()
        
    }
  
    
    @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)
            }
        }
    }
    
    func setupHomeMarker() {
        
        if let icon = UIImage(named: "location-home"){
            if #available(iOS 13.0, *) {
                marker_home_icon.image = icon.withRenderingMode(.alwaysTemplate)
                marker_home_icon.tintColor = Colors.primaryColor
            }
        }
        
    }
    
    func setupSaveBotton(){
    
        //self.save_location_btn.roundCorners(corners: [.topLeft, .topRight], radius: 20)
        self.save_location_btn.setTitle("Save location".localized, for: .normal)
        self.save_location_btn.initBoldFont()
        self.save_location_btn.setTitleColor(.white, for: .normal)
        
        self.save_location_btn.backgroundColor = Colors.primaryColor
        self.save_btn_container.backgroundColor = Colors.primaryColor
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupHomeMarker()
        self.setupSaveBotton()
        
        //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()
        
        
        
        if let lat = picked_lat, let lng = picked_lng{
            
            picked_lat = lat
            picked_lng = lng
            
            if let address = picked_address{
                topBarTitle.text = address
            }
            
            
            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 12.0)
            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: 17)
                viewContainer.addSubview(mapView)
                
                // Creates a marker in the center of the map.
                let marker = GMSMarker()
                marker.position = CLLocationCoordinate2D(latitude:  lat, longitude: lng)
                marker.map = mapView
                
            }
            
            
        }else if let guest = Guest.getInstance() {
            
            self.latitude = guest.lat
            self.longitude = guest.lng
            
            let camera = GMSCameraPosition.camera(withLatitude: guest.lat, longitude: guest.lng, zoom: 12.0)
            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)
                
                
            }
           
        }else if let lat = self.latitude, let lng = self.longitude{
            
            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lng, zoom: 12.0)
            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: 17)
                viewContainer.addSubview(mapView)
                
            }
            
        }
        
     
        
    }

    
    
    
    
    func startAutocompleteController() {
           
        let autocompleteController = GMSAutocompleteViewController()
        autocompleteController.delegate = self
           
        autocompleteController.tableCellBackgroundColor = .white
        autocompleteController.tintColor = .white
    
        
        let fields0: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |  UInt(GMSPlaceField.coordinate.rawValue) |
            UInt(GMSPlaceField.addressComponents.rawValue) |
                                                    UInt(GMSPlaceField.placeID.rawValue))
        
           autocompleteController.placeFields = fields0

           // Specify a filter.
           let filter = GMSAutocompleteFilter()
            //filter.type = .address
           autocompleteController.autocompleteFilter = filter

           // Display the autocomplete view controller.
            self.present(autocompleteController, animated: true, completion: nil)
       }
    
    ///API
    

    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
    }
    

    
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        
        if(marker.iconView != nil ){
           
        }

        return true
    }
  
 
}



extension LocationPickerViewController: GMSAutocompleteViewControllerDelegate {

  // Handle the user's selection.
  func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
    
  
    self.picked_address = place.name
    self.picked_lat = place.coordinate.latitude
    self.picked_lng = place.coordinate.longitude

    self.current_lat = place.coordinate.latitude
    self.current_lng = place.coordinate.longitude
    
    let camera = GMSCameraPosition.camera(withLatitude: picked_lat!, longitude: picked_lng!, zoom: 6.0)
    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)
        
    }
    
    
    topBarTitle.text = picked_address!
    
    viewController.dismiss(animated: true)
 
  }

  func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
    // TODO: handle the error.
    print("Error: ", error.localizedDescription)
  }

  // User canceled the operation.
  func wasCancelled(_ viewController: GMSAutocompleteViewController) {
    viewController.dismiss(animated: true, completion: nil)
  }

  // Turn the network activity indicator on and off again.
  func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
  }

  func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
  }

}

