//
//  MainViewController.swift
//  Em-call
//
//  Created by Alex Sh on 21.02.2022.
//

import UIKit
import MapKit


class CustomPointAnnotation: MKPointAnnotation {
    var imageName: String!
}


class MainViewController: UIViewController, UITextFieldDelegate, MKMapViewDelegate
{
    @IBOutlet weak var text_Location: UITextField!
    var count:Int = 0
    var settingsLauncher:SettingsLauncher = SettingsLauncher()
    var bottomSheetVC:UIViewController? = nil
    var selRow:Int = 0
    var showWorkerMap = 0
    
    @IBOutlet weak var buttonElectric: UIButton!
    @IBOutlet weak var butHandyman: UIButton!
    @IBOutlet weak var butLocksmith: UIButton!
    @IBOutlet weak var butPlumber: UIButton!
    
    @IBAction func pressButMenu(_ sender: Any) {
        guard let navVC = self.navigationController
        else { return }
        settingsLauncher.showSettings(navigVC: navVC,dispatcher:2)
 
    }
 
    @IBOutlet weak var butMenu: UIButton!
    // Expand/Collapse the side menu by changing trailing's constant
 
    @IBOutlet weak var buttonWhatDo: UIButton!
    @IBOutlet weak var imgMicrophon: UIImageView!
    @IBOutlet weak var bottomView: UIView!
 
    @IBOutlet weak var buttonDoIt: UIButton!
    var showAlert:ShowAlert = ShowAlert()
    var arrayCoordMapWorker = [(51.51455283,-0.12197132),(51.5121277776,-0.120492655896),(51.515234854,-0.115117274),(51.5103413836,-0.1215190233),(51.51304096,-0.126825408),
                               (51.5089155267,-0.1272603095),
                               /*worker go*/(51.51379832395,-0.123224424264)]
    var nameImageIconMap = ["electric_map2","plumber_map2","handyman_map2","worker_map2"]
    var indexNameImageIconMap = 0
    @IBOutlet weak var mapView: MKMapView!
    

    let locationManager = LocationMng()
                    // var detailsController:MainChildViewController?
    @IBOutlet weak var buttonEmerElectric: UIButton!
    @IBOutlet weak var buttonLockUp: UIButton!
    
    @IBOutlet weak var buttonEmergency: UIButton!
    @IBOutlet weak var buttonEmerHandman: UIButton!
    @IBOutlet weak var buttonEmerPlumber: UIButton!
    @IBAction func pressEmerHandman(_ sender: Any) {
    }
    @IBAction func pressEmerPlumber(_ sender: Any) {
        
    }
    @IBAction func pressEmerElectric(_ sender: Any) {
    }
    
    @IBAction func pressEmergency(_ sender: Any) {
        buttonLockUp.isHidden = false
        buttonEmerElectric.isHidden = false
        buttonEmerPlumber.isHidden = false
        buttonEmerHandman.isHidden = false
        buttonEmergency.isHidden = false
        //self.View = UIView()
        self.view.isOpaque = false // сообщаем системе что myView будет иметь полупрозрачные нарисованные элементы
        count = count + 1
        if count%2 == 1 {
        self.view.alpha = 0.7 // прозрачность всего UIView
        } else {
            self.view.alpha = 1.0
        }
        self.navigationController?.setNavigationBarHidden(true, animated: true)
     }

    @IBAction func longPress(_ sender: Any) {
        let pressPoint = (sender as AnyObject).location(in:mapView)
       // let pressCoordinate = mapView.convert(pressPoint, to: mapView)
        let pressCoordinate = mapView.convert(pressPoint, toCoordinateFrom: mapView)
        removeSpecificAnnotation(titleAnnot: "My place")
        let myposannot = CustomPointAnnotation()

                myposannot.coordinate = pressCoordinate
                myposannot.title = "My place"
                myposannot.subtitle = "I am here!"
                myposannot.imageName = "eva_pin-fill_red3"
                mapView.addAnnotation(myposannot)
        //let countAnnot = mapView.annotations.count
        let anno = findSpecificAnnotation(titleAnnot: "My place")
        if anno != nil {
            mapView.selectAnnotation(anno as! MKAnnotation, animated: true)
        }
            let getLat: CLLocationDegrees = pressCoordinate.latitude
            let getLon: CLLocationDegrees = pressCoordinate.longitude
            let locationTouch: CLLocation =  CLLocation(latitude: getLat, longitude: getLon)
            coordinateToAdress(locationTouch)
    }

    @IBAction func pressElectric(_ sender: Any) {
        //let storyboard = UIStoryboard(name: "Main", bundle: nil)
        // var vc:UINavigationController
       //  let tabBar = storyboard.instantiateViewController(withIdentifier: "TabBar")
       //let vc = storyboard.instantiateViewController(withIdentifier: "Electric") as! ElectricTableViewController
         let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NaviElectric") as! UINavigationController
       //  vc = UINavigationController.init(rootViewController: tabBar)
        //// vc.pushViewController(tabBar, animated: true)
        navigationController?.present(vc, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
               //London coordinates
        let initialLocation = CLLocation(latitude: 51.509865, longitude: -0.118092)
        mapView.centerToLocation(initialLocation)
        buttonEmergency.isHidden = false
        buttonLockUp.isHidden = true
        buttonEmerElectric.isHidden = true
        buttonEmerPlumber.isHidden = true
        buttonEmerHandman.isHidden = true
         
        text_Location.delegate = self
        self.mapView.delegate = self
 /*
         let annotations = MKPointAnnotation()
            annotations.title = "Set my location"
            annotations.coordinate = CLLocationCoordinate2D(latitude: 51.509865, longitude: -0.118092)
            mapView.addAnnotation(annotations)*/               // settingsLauncher.delegate = self
        navigationController?.navigationBar.titleTextAttributes = [.foregroundColor:UIColor(red: 0 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1.0)]
       // let leftBarButtonItem = UIBarButtonItem(image: UIImage(contentsOfFile: "akar-icons_arrow-left"), style: .plain, target: self, action:Selector("pressEmerElectric"))       // self.navigationItem.leftBarButtonItem = leftBarButtonItem
       // self.locationManager.delegate = self
               
        for coord in arrayCoordMapWorker {
            let annotations = CustomPointAnnotation()
            annotations.coordinate = CLLocationCoordinate2D(latitude:
                                                                coord.0, longitude: coord.1)
            annotations.imageName = nameImageIconMap[indexNameImageIconMap]
            
            indexNameImageIconMap = indexNameImageIconMap + 1
            if indexNameImageIconMap > 2 {
                indexNameImageIconMap = 0 }
            annotations.title = "Worker Place"
            mapView.addAnnotation(annotations)
        }
                // tableView.tableFooterView = UIView()
        self.settingsLauncher.delegateMenu = self
  
    }
    
    override func viewDidAppear(_ animated:Bool) {
        super.viewDidAppear(animated)
        locationManager.checkLocationEnable()
        buttonEmergency.isHidden = false
        buttonLockUp.isHidden = true
        buttonEmerElectric.isHidden = true
        buttonEmerPlumber.isHidden = true
        buttonEmerHandman.isHidden = true
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
        if bottomSheetVC != nil {
                            //sendSubviewToBack(_ view: UIView)
            self.view.sendSubviewToBack(bottomSheetVC!.view)
                                // self.view.willRemoveSubview(bottomSheetVC!.view)
            bottomSheetVC!.removeFromParent()
        }
        if showWorkerMap == 1 //переход из CallProfiViewController
        {
            let annotations = CustomPointAnnotation()
            let coord = arrayCoordMapWorker[3]
            annotations.coordinate = CLLocationCoordinate2D(latitude: coord.0, longitude: coord.1)
            annotations.imageName = nameImageIconMap[3]
             mapView.addAnnotation(annotations)
            
            text_Location.isHidden = true
            buttonWhatDo.isHidden = true
            buttonDoIt.isHidden = true
            imgMicrophon.isHidden = true
        }  else {
            text_Location.isHidden = false
            buttonWhatDo.isHidden = false
            buttonDoIt.isHidden = false
            imgMicrophon.isHidden = false
        }
       // mapView.selectAnnotation(mapView.annotations[0], animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
      /*  self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
        self.navigationController?.navigationBar.barTintColor = UIColor.black
        self.navigationController?.navigationBar.topItem?.title = "LOGO"
        self.navigationController?.navigationItem.title = "LOGO"*/
       // self.view.removeFromSuperview()
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.view.alpha = 1.0
        count = 0
        showWorkerMap = 0
    }
    
    @IBAction func pressWhatDo(_ sender: Any) {
        addBottomSheetView()
    }
    
    func removeSpecificAnnotation(titleAnnot:String) {
        for annotation in self.mapView.annotations {
            if let title = annotation.title, title == titleAnnot {
                self.mapView.removeAnnotation(annotation)
            }
        }
    }
    
    func findSpecificAnnotation(titleAnnot:String)->AnyObject? {
       // var annot:MKAnnotation? = nil
        for annotation in self.mapView.annotations {
            if let title = annotation.title, title == titleAnnot {
               // self.mapView.removeAnnotation(annotation)
                return annotation
            }
        }
        return nil
    }
    
    func addBottomSheetView() {
        // 1- Init bottomSheetVC

        bottomSheetVC = SmallListWorkVC()
      
       // mapView.isHidden = true
       // bottomView.isHidden = true
        // 2- Add bottomSheetVC as a child view
        if bottomSheetVC != nil {
            self.addChild(bottomSheetVC!)
        self.view.addSubview(bottomSheetVC!.view)
        bottomSheetVC!.didMove(toParent: self)

        // 3- Adjust bottomSheet frame and initial position.
        let height = view.frame.height
        let width  = view.frame.width
        bottomSheetVC!.view.frame = CGRect(x: 0, y: self.view.frame.maxY, width: width, height: height)
        }
        // bottomSheetVC.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
    }
 
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
       /*    let item = UIBarButtonItem(title: "LOGO", style: .plain, target: nil, action: nil)
           viewController.navigationItem.backBarButtonItem = item*/
       }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        text_Location.resignFirstResponder()
    }
    
    //func mapView(mapViewAnnot: MKMapView!,ViewForAnnotation annotation: MKAnnotation!) ->MKAnnotationView{
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) ->MKAnnotationView? {
        if !(annotation is CustomPointAnnotation) {
             return MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
         }
         let reuseId = "pin"
        
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
                if pinView == nil {
                    pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
                    pinView?.canShowCallout = true
                }
                else {
                    pinView?.annotation = annotation
                    pinView?.canShowCallout = true
                   // pinView.animatesDrop = true
                   // pinView.pinTintColor = UIColor.darkGrayColor
                    pinView?.isDraggable = true
                    pinView?.accessibilityLabel = "hello"
                    let btn = UIButton(type: .detailDisclosure)
                    pinView?.rightCalloutAccessoryView = btn
                }
        /*var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
           if(pinView == nil){             pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
             pinView!.canShowCallout = true             pinView!.animatesDrop = true            pinView!.pinTintColor = .red
         } else {             pinView!.annotation = annotation         }*/
        let cpa = annotation as! CustomPointAnnotation
        if cpa.imageName != "eva_pin-fill_red3"  {
        pinView!.image = UIImage(named:cpa.imageName)
        }  else {
            pinView!.image = UIImage(named: "eva_pin-fill_red3")
        }
         return pinView!
     }

    @IBAction func tapGesture(_ sender: Any) {
        view.endEditing(true)
    }
    // Преобразуем координаты в Адрес
    func coordinateToAdress(_ locations: CLLocation)  {
        CLGeocoder().reverseGeocodeLocation(locations /*.last!*/) { (placemarks, error) in
            // Детализированная информация по точке
            var placemark: CLPlacemark!
             if let placemarks = placemarks {
                placemark = placemarks[0]
            }          /*   guard let country = placemark.addressDictionary!["Country"] as? String
             else {               // print("Country name \(country)")
                return            }            guard let city:String = (placemark.addressDictionary!["City"] as? String)
            else {    //print("City name \(city)")                return            }*/
             guard let street = placemark.addressDictionary!["Street"] as? String
            else {
                return// print(street)
            }
             guard let subLocality = placemark.addressDictionary!["SubLocality"] as? String
            else {
                return// print(subLocality)
            }
            self.text_Location.text = street + " , " + subLocality
  
        }
    }
}

private extension MKMapView {
  func centerToLocation(
    _ location: CLLocation,
    regionRadius: CLLocationDistance = 1000
  ) {
    let coordinateRegion = MKCoordinateRegion( center: location.coordinate,
      latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
    setRegion(coordinateRegion, animated: true)
  }
}


extension MainViewController:SettingsLauncherDelegate {
    func settingsDelegateClick(img: UIImage?,selRow:Int,imgName:String?) {
        if img != nil {
           // images.append(img!)
           // collectionView.reloadData()
        }
        else {
            self.selRow = selRow
        }
   
    }
}

//MenuViewControllerDelegate

extension MainViewController: MenuViewControllerDelegate {
    func selectedMenuCell(_ row: Int) {
        switch row {
        case 0: break
            // Home
          case 1: break
            // Music
           // self.showViewController(viewController: UINavigationController.self, storyboardId: "MusicNavID")
        case 2: //break
            // Movies
           self.showMenuViewController(viewController: MapViewController.self, storyboardId: "Map")
        case 3: //break
            // Books
            self.showMenuViewController(viewController: VKBookingViewController.self, storyboardId: "BookingVK")
        case 4: break
            // Profile
           // let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
          //  let profileModalVC = storyboard.instantiateViewController(withIdentifier: "ProfileModalID") as? ProfileViewController
          //  present(profileModalVC!, animated: true, completion: nil)
        case 5: break
            // Settings
          //  self.showViewController(viewController: UINavigationController.self, storyboardId: "SettingsNavID")
        case 6: break
            // Like us on facebook
          //  let safariVC = SFSafariViewController(url: URL(string: "https://www.facebook.com/johncodeos")!)
           // present(safariVC, animated: true)
        default:
            break
        }
    }
    
    func showMenuViewController<T: UIViewController>(viewController: T.Type, storyboardId: String) -> () {
          // Remove the previous View
          for subview in view.subviews {
              if subview.tag == 99 {
                   subview.removeFromSuperview()
              }
          }
          let storyboard = UIStoryboard(name: "Main", bundle: nil)
          let vc = storyboard.instantiateViewController(withIdentifier: storyboardId) as! T
          vc.view.tag = 99

        navigationController?.pushViewController(vc , animated: true)
 
          vc.didMove(toParent: self)
      }
    
}

/*
extension UIViewController {
    
    // With this extension you can access the MainViewController from the child view controllers.
    func revealViewController() -> MainViewController? {
        var viewController: UIViewController? = self
        
        if viewController != nil && viewController is MainViewController {
            return viewController! as? MainViewController
        }
        while (!(viewController is MainViewController) && viewController?.parent != nil) {
            viewController = viewController?.parent
        }
        if viewController is MainViewController {
            return viewController as? MainViewController
        }
        return nil
    }
    
}*/
