package com.example.unodtantos.appqueology2.controlador;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.unodtantos.appqueology2.R;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by unodtantos on 27/05/2015.
 */
public class GPSTracker extends Service implements LocationListener {

    /*--------------------------------------------------------------------------------------------*/

    // <editor-fold defaultstate="collapsed" desc="Aributos de la clase">

    private final Context mContext;
    private Typeface font;
    private String nombre_p;
    private boolean isGPSEnabled = false;
    private boolean isNetworkEnabled = false;
    private boolean canGetLocation = false;
    private Location location;
    private double latitude;
    private double longitude;
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 metros  // La mínima distancia pra cambiar el Update en metros.
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;  // 1 minuto   // El mínimo de tiempo entre updates en milisegundos.
    protected LocationManager locationManager;
    private Uri uri;
    private String photoCode;
    private String date2;
    protected Context context;
    private final String ruta_fotos = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/misfotos/";
    private File file = new File(ruta_fotos);

    // </editor-fold>

    /*--------------------------------------------------------------------------------------------*/

    // <editor-fold defaultstate="collapsed" desc="Constructor de la clase">

    /**
     * Constructor de la clase.
     * @param context
     * @param nombre_proyecto
     */
    public GPSTracker(Context context, String nombre_proyecto) {
        this.mContext = context;
        this.nombre_p = nombre_proyecto;
        this.font = Typeface.createFromAsset(this.mContext.getAssets(), "gloriahallelujah.ttf");
        getLocation();
    }

    // </editor-fold>

    /*--------------------------------------------------------------------------------------------*/

    // <editor-fold defaultstate="collapsed" desc="Obtencion del punto GPS">

    /**
     * Método que se encarga de obtener el punto GPS
     * @return
     */
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // No network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Método que se encarga de deterner el uso del GPS.
     */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Método que se encarga de comprobar si se encuentran habilitados los servicios de GPS.
     * @return
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    @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;
    }

    // </editor-fold>

    /*--------------------------------------------------------------------------------------------*/

    // <editor-fold defaultstate="collapsed" desc="Alert">

    /**
     * Método que se encarga de configurar el Alert que preguntará al usuario si desea activar el
     * servicio de GPS.
     */
    public void alertHabilitarServicios(){

        LayoutInflater li = LayoutInflater.from(mContext);
        View promptsView = li.inflate(R.layout.activity_dialogo_activar_gps, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
        alertDialogBuilder.setView(promptsView);

        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("Activar GPS", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                })
                .setNegativeButton("Sacar foto sin GPS", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String path = file.getPath();

                        if (!file.exists()) {
                            Boolean c = file.mkdirs();
                        }

                        String _Date = "2015-05-27 08:45:22";
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
                        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
                        String date = dateFormat.format(new Date());
                        date2 = dateFormat2.format(new Date());
                        photoCode = "pic_" + date;

                        String file = ruta_fotos + photoCode + ".jpg";
                        File mi_foto = new File( file );

                        try {
                            mi_foto.createNewFile();
                        } catch (IOException ex) {

                        }
                        uri = Uri.fromFile(mi_foto);
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        ((Activity) mContext ).startActivityForResult(cameraIntent, 0);
                        dialog.cancel();

                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

        aspectoAlert(alertDialog, promptsView);
    }

    // </editor-fold>

    /*--------------------------------------------------------------------------------------------*/

    // <editor-fold defaultstate="collapsed" desc="Aspecto alert">

    /**
     * Método que se encarga de darle aspecto al Alert anteriormente mencionado.
     * @param alertDialog
     * @param promptsView
     */
    private void aspectoAlert(AlertDialog alertDialog, View promptsView){

        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        TextView titulo = (TextView) promptsView.findViewById(R.id.fuente32);
        TextView mensaje = (TextView) promptsView.findViewById(R.id.fuente33);
        titulo.setTypeface(this.font);
        mensaje.setTypeface(this.font);

        aspectoBotonesPosNeg(alertDialog);
    }

    /**
     * Método que se encarga de darle aspecto a los botones "Aceptar" y "Cancelar" del Alert
     * que nos ocupa.
     * @param alertDialog
     */
    private void aspectoBotonesPosNeg(AlertDialog alertDialog){

        Button btn_cancelar = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        Button btn_aceptar = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);

        if(btn_cancelar != null && btn_aceptar != null){

            btn_aceptar.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.dialog_button_selector));
            btn_aceptar.setTextColor(Color.WHITE);
            btn_aceptar.setTypeface(this.font);
            btn_cancelar.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.dialog_button_selector));
            btn_cancelar.setTextColor(Color.WHITE);
            btn_cancelar.setTypeface(this.font);

            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btn_aceptar.getLayoutParams();
            params.setMargins(20, 0, 0, 0);
            btn_aceptar.setLayoutParams(params);
        }
    }

    // </editor-fold>

    /*--------------------------------------------------------------------------------------------*/

    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">

    public Uri getUri() {
        return uri;
    }

    public void setUri(Uri uri) {
        this.uri = uri;
    }

    public String getPhotoCode() {
        return photoCode;
    }

    public void setPhotoCode(String photoCode) {
        this.photoCode = photoCode;
    }

    public String getDate() {
        return date2;
    }

    public void setDate(String date) {
        this.date2 = date;
    }

    // </editor-fold>

    /*-------------------------------------------------------------------------------------------------*/
}