//
//  OTextField.swift
//  NSApplication1.8
//
//  Created by DT Team  on 5/9/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import UIKit
import SkyFloatingLabelTextField
import GooglePlaces


class OAddressLocationField : UIStackView, OFieldDelegate{
   
    func getKey() -> String {
        return field!.label
    }
    
    func getField() -> CField? {
        return field
    }
       
    func getValue() -> String {
        if let address = response_address, let lat = response_lat, let lng = response_lng{
            return "\(address.trimmingCharacters(in: .whitespacesAndNewlines));\(lat);\(lng)"
        }else if let address = response_address{
            return "\(address);"
        }
        
        
        return ""
    }
    
    var viewController: UIViewController?
    var response_address: String?
    var response_lat: String?
    var response_lng: String?
    
    static func newInstance() -> OAddressLocationField{
        
        let stackView =  OAddressLocationField( frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.distribution = .fillProportionally
        stackView.spacing = CGFloat(5)
        stackView.backgroundColor = .orange
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        return stackView
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    
    var labelView: SkyFloatingLabelTextField = SkyFloatingLabelTextField(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
    let button = UIButton(frame: CGRect(x: 10, y: 20, width: 50, height: 50))
    var field: CField?
    
    func setup(field: CField) ->  OAddressLocationField{
    
         self.field = field
    
        
        
        if field.required == 1{
            labelView.placeholder = field.label+" (*)"
        }else{
            labelView.placeholder = field.label
        }
        
        
        labelView.title = field.label
        addArrangedSubview(labelView)
        
        
        labelView.textColor = UIColor.black
        labelView.lineColor = UIColor.gray
        labelView.selectedTitleColor = UIColor.black
        labelView.selectedLineColor = Colors.primaryColor
        labelView.selectedLineHeight = 1.5
        labelView.lineHeight = 0.5
        labelView.titleColor = Colors.primaryColor
        labelView.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 16)
        labelView.titleFont = UIFont(name: AppConfig.Design.Fonts.regular, size: 16)!
        labelView.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        
        
        labelView.inputAccessoryView = setupDoneButtonOnKeyboard()
        
        button.addTarget(self, action: #selector(self.getLocation(_:)), for: .touchUpInside)
        button.setTitle("", for: .normal)
        button.backgroundColor = .gray
        
        button.setIcon(icon: .ionicons(.androidLocate), iconSize: 22, color: .gray, forState: .normal)

        addArrangedSubview(button)
        
        return self
        
    }
    
    
    
       // This will notify us when something has changed on the textfield
       @objc func textFieldDidChange(_ textfield: UITextField) {
           if let text = textfield.text {
               if let floatingLabelTextField = textfield as? SkyFloatingLabelTextField {
                    floatingLabelTextField.errorMessage = ""
               }
           }
       }
       
    
    @objc func getLocation(_ sender: UIButton){ //<- needs `@objc`
        
        startAutocompleteController()
        
    }
    
    
    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.
            if let controller = self.viewController{
                controller.present(autocompleteController, animated: true, completion: nil)
            }
           
       }

    
       func setupDoneButtonOnKeyboard() -> UIToolbar
       {
           let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x:0, y:0, width:320, height:50))
           doneToolbar.barStyle = UIBarStyle.default

        let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let done: UIBarButtonItem = UIBarButtonItem(title: "Done".localized, style: UIBarButtonItem.Style.done, target: self, action: #selector(doneButtonAction))

           let items = NSMutableArray()
           items.add(flexSpace)
           items.add(done)

           doneToolbar.items = items as? [UIBarButtonItem]
           doneToolbar.sizeToFit()
           
           return doneToolbar
          
       }
       
       @objc func doneButtonAction()
       {
           labelView.resignFirstResponder()
       }
    
    
}



extension OAddressLocationField: GMSAutocompleteViewControllerDelegate {

  // Handle the user's selection.
  func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
    
   /* print("Place name: \(place.name)")
    print("Place address: \(place.formattedAddress)")
    print("Place ID: \(place.placeID)")
    print("Place coordinate: \(place.coordinate)")
    print("Place addressComponents: \(place.addressComponents)")*/
    
    response_address = place.name
    response_lat = "\(place.coordinate.latitude)"
    response_lng = "\(place.coordinate.longitude)"

    labelView.text = place.name
    button.setIcon(icon: .ionicons(.androidLocate), iconSize: 22, color: Colors.primaryColor, forState: .normal)
    
    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
  }

}


