//
//  ViewController.swift
//  Trolley App
//
//  Created by Kendrick Morales on 10/21/19.
//  Copyright © 2019 Kendrick Morales. All rights reserved.
//

import UIKit
import CoreLocation
import MapKit
import Alamofire



class ViewController: UIViewController,  CLLocationManagerDelegate {

    var estado = false
    let locationManager = CLLocationManager()
   
   
    var locations: CLLocation!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.requestAlwaysAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        }

        // Do any additional setup after loading the view.
    }
    
    //funcion para poder extraer latitud y longitud
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate
            else { return }
        print("locations = \(locValue.latitude) \(locValue.longitude)")
        
        
        
    }
 
    
    
    //botton de las tracking
    @IBAction func trackingButton(_ sender: UIButton) {
        
        // si el estado esta en falso
        if estado != true{
         sender.setTitle("Stop", for: .normal) // cambia el texto del boton
         estado = true // cambiamos el estado a activado
         locationManager.startUpdatingLocation() // activamos el metodo de capturacion de localizacion
        }
        else{ // si el estado esta en cierto
             sender.setTitle("Tracking", for: .normal) // cambiamos el texto del boton
            locationManager.stopUpdatingLocation() // paramos el metodo de capturacion de localizacion
            locations = locationManager.location
            //print("pollo"+"\(latitud.coordinate.latitude)")
           
            
            let location: [String: Any] = ["latitude": locations.coordinate.latitude,"longitude": locations.coordinate.longitude]
       //conect to server and send lat y long
            
            AF.request("http://136.145.231.39/json-receiver.php", method:.post, parameters: location,encoding: JSONEncoding.default).response{ (response) in
      print(response)
            }
            
        AF.request("http://136.145.231.39/sender2.php").responseJSON { response in
            debugPrint("Response: \(response)")
            
        }
            
        
            estado = false // se cambia estado de nuevo a falso
        }
    }

}

