package com.virtual.tour.arquelogia.modelo;


/**
 * Created by Roger Gomez
 */

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

import com.virtual.tour.arquelogia.R;


public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // Status del GPS.
    boolean isGPSEnabled = false;
    boolean canGetLocation = false;

    Location location; // localización.
    double latitude; // latitud.
    double longitude; // longitud.
    float bearing;

    // ditancia minima entre updates del GPS
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 metros

    // Tiempo mínimo entre updates del GPS
    private static final long MIN_TIME_BW_UPDATES = 1000 * 1 * 1; // 1 minuto.

    // Location Manager
    protected LocationManager locationManager;


    /**
     * Constructor de la Clase
     *
     * @param context Contexto de la activity principal
     */

    public GPSTracker(Context context) {
        this.mContext = context;
    }


    /**
     * Función que Devuele la localizacion del dispositvo mediante el GPS
     *
     * @return
     */

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            location = null;

            // status el GPS.
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            if (isGPSEnabled) {
                this.canGetLocation = true;
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        bearing=location.getBearing();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }

    /**
     * Funcón que detiene el listener del GPS
     */

    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Función que devuelve la latitud
     */

    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        return latitude;
    }

    /**
     * Function que devuelve la Longitud
     */

    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        return longitude;
    }

    /**
     * Función que devuelve la direccion de un punto
     */

    public float getBearing() {
        if (location != null) {
            bearing = location.getBearing();
        }
        return bearing;
    }

    /**
     * Función que devuelve si el  GPS/wifi esta activo.
     *
     * @return boolean
     */

    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Función donde si el GPS/wifi no está activo,
     * pedimos al usuario si desea ir a la configuración para activarlo.
     */

    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Titulo del Alert
        alertDialog.setTitle(R.string.gps);

        // Mensaje del Alert
        alertDialog.setMessage(R.string.gps_desactivado);

        // Button Configuración
        alertDialog.setPositiveButton(R.string.configuracion, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // Bptón Cancelar
        alertDialog.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Mostrar mensaje
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}