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

import UIKit
import MapKit


class MainViewController: UIViewController, UITextFieldDelegate  //, CLLocationManagerDelegate
{
    @IBOutlet weak var text_Location: UITextField!
    var count:Int = 0
   // var settingsLauncher:SettingsLauncher = SettingsLauncher()
    var bottomSheetVC:UIViewController? = nil
    var selRow:Int = 0
    
    @IBOutlet weak var bottomView: UIView!
   
    //    @IBOutlet weak var swipeableView: SwipeableView!
    //  @IBOutlet weak var swipeableView: MKMapView!
    var showAlert:ShowAlert = ShowAlert()
    @IBOutlet weak var mapView: MKMapView!
    //let locationManager = LocationMng(mainView:self)
    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
        }
     }

    @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)
  
        let myposannot = MKPointAnnotation()

                myposannot.coordinate = pressCoordinate
                myposannot.title = "My place"
                myposannot.subtitle = "I am here!"
        mapView.addAnnotation(myposannot)
        
        let getLat: CLLocationDegrees = pressCoordinate.latitude
            let getLon: CLLocationDegrees = pressCoordinate.longitude
            let locationTouch: CLLocation =  CLLocation(latitude: getLat, longitude: getLon)
            coordinateToAdress(locationTouch)

    }
   /*
    private func setupSwipeable() {
        self.swipeableView.isPanGestureInverted = true
        self.swipeableView.flexibleLayout = .init(with: flexLayout, end: view.frame.height / 2)
        self.swipeableView.childViewInteractionOnExpandedOnly = false
        self.swipeableView.indicatorColors = (UIColor.Showcase8.colorB4,UIColor.Showcase8.colorB1)
    }
    
    private func setupChildview() {
        if let characterPickerView = self.storyboard?.instantiateViewController(withIdentifier:"child_Id8") as? ShowcaseChildViewController_8 {
            self.characterPickerView = characterPickerView
            // plug the child view into the swipeable view
            self.swipeableView.setChildView(childVC: characterPickerView, parentVC: self)
            // plug the character picker delegate
            characterPickerView.delegate = self
        }
    }
    */
    override func viewDidLoad() {
        super.viewDidLoad()
      //  setupBackButton()
       // self.navigationItem.titleView?.isHidden = false
       /* self.title = "LOGO"
        self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
        self.navigationController?.navigationBar.barTintColor = UIColor.black
        self.navigationItem.title = "LOGO"
           
        self.navigationController?.navigationBar.topItem?.title = "Logo"
        self.navigationController?.navigationItem.title = "Logo"*/
            //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
 /*
         let annotations = MKPointAnnotation()
            annotations.title = "Set my location"
            annotations.coordinate = CLLocationCoordinate2D(latitude: 51.509865, longitude: -0.118092)
            mapView.addAnnotation(annotations)*/
               // settingsLauncher.delegate = 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()
        }
    }
    
    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
    }
    
    @IBAction func pressWhatDo(_ sender: Any) {
        addBottomSheetView()
    }
    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)
    }
    /*
    @IBAction func pressRowSelect(_ sender: Any) {
       // guard let navVC = self.navigationController
       // else { return }
      //  settingsLauncher.showSettings(navigVC: navVC,dispatcher:1)
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc:UIViewController
        if #available(iOS 13.0, *) {
             vc = storyboard.instantiateViewController(identifier: "ListWork") as! ListWorkViewController
        } else {
            vc = storyboard.instantiateViewController(withIdentifier: "ListWork")
        }
         navigationController?.pushViewController(vc, animated: true)
    }*/
    
    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{
  
         let reuseId = "pin"

        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
         }
         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) {
        if img != nil {
           // images.append(img!)
           // collectionView.reloadData()
        }
        else {
            self.selRow = selRow
        }
   
    }
}
