package es.upvmaster.fullmediaplayer;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.services.drive.Drive;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.regex.Pattern;

/**
 * Created by crpor on 31/08/2016.
 */
public final class Libreria {
    enum TipoLog {DEBUG,ERROR};
    enum TipoMedio {LOCAL, URL};
    enum ArchivosValidos {MUSICA, VIDEO};
    enum ElementosValidos {MEDIO, LISTA};


    static String[] extensionesVideo = {".3gp", ".mp4", ".ts", ".mkv", ".webm"};
    static String[] extensionesMusica = {".mp3", ".mid", ".xmf", ".mxmf", ".rtttl", ".rtx", ".ota", ".imy", ".ogg", ".mka", ".wav", ".webm", ".m4a", ".aac", ".flac"};

    static final int SOLICITUD_SELECCION_CUENTA = 10;
    static final int SOLICITUD_AUTORIZACION = 11;

    static Drive servicio = null;
    static GoogleAccountCredential credencial = null;
    static String nombreCuenta = null;

    static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    static final String DISPLAY_MESSAGE_ACTION ="es.masterupv.fullmediaplayer.DISPLAY_MESSAGE";

    private static Handler manejador = new Handler(Looper.getMainLooper());
    static void mostrarMensaje(final Context context, final String mensaje) {
        manejador.post(new Runnable() {
            public void run() {
                Toast.makeText(context, mensaje, Toast.LENGTH_SHORT).show();
            }
        });
    }

    static void imprimirLog(TipoLog tipoLog,String etiqueta,String mensaje) {
        if (mensaje!=null) {
            if (tipoLog == TipoLog.DEBUG)
                Log.d(etiqueta, mensaje);
            else
                Log.e(etiqueta, mensaje);
        }
    }

    private static Handler carga = new Handler(Looper.getMainLooper());
    private static ProgressDialog dialogo;
    static void mostrarCarga(final Context context, final String mensaje) {
        carga.post(new Runnable() {
            public void run() {
                dialogo = new ProgressDialog(context);
                dialogo.setMessage(mensaje);
                dialogo.setCancelable(false);
                dialogo.show();
            }
        });
    }

    static void ocultarCarga(final Context context) {
        carga.post(new Runnable() {
            public void run() {
                try {
                    dialogo.dismiss();
                } catch (Exception e) {
                    imprimirLog(TipoLog.ERROR,"Ocultar carga", e.getMessage());
                }
            }
        });
    }

    static boolean esNumericoCorrecto(String pin,int longitud) {
        Pattern patron = Pattern.compile("^[0-9]{"+longitud+"}$");
        return patron.matcher(pin).matches();
    }

    static void iniciarReproduccion(Context context, TipoMedio tipomedio, String ruta) {
        Intent intent = new Intent(context, ReproductorWeb.class);
        intent.putExtra("Tipo", tipomedio.toString());
        intent.putExtra("Ruta", ruta);
        context.startActivity(intent);
    }

    static void guardarImagenURL(String url) {
        String nombreFichero = url.substring(url.lastIndexOf("/")+1);
        if (nombreFichero.indexOf(".jpg")>0 || nombreFichero.indexOf(".png")>0 || nombreFichero.indexOf(".gif")>0) {
            HttpURLConnection conn = null;
            File file = null;
            FileOutputStream fileOutput = null;
            URL imageUrl = null;
            try {
                file = new File(InfoGlobal.getINSTANCIA().getDirectorio(),nombreFichero);
                if (!file.exists()) {
                    imageUrl = new URL(url);
                    conn = (HttpURLConnection) imageUrl.openConnection();
                    conn.setDoOutput(false);
                    conn.setRequestMethod("GET");
                    conn.connect();
                    fileOutput = new FileOutputStream(file);
                    InputStream inputStream = conn.getInputStream();
                    int downloadedSize = 0;
                    byte[] buffer = new byte[1024];
                    int bufferLength = 0;
                    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                        fileOutput.write(buffer, 0, bufferLength);
                        downloadedSize += bufferLength;
                    }

                    conn.disconnect();
                }
            } catch (MalformedURLException e) {
                imprimirLog(TipoLog.ERROR,"Guardar Imagen",e.getMessage());
            } catch (IOException e) {
                imprimirLog(TipoLog.ERROR,"Guardar Imagen IO",e.getMessage());
            } finally {
                try {
                    if (fileOutput != null) fileOutput.close();
                    if (file.exists() && BitmapFactory.decodeFile(file.getAbsolutePath())==null) file.delete();
                } catch (IOException e) {
                    imprimirLog(TipoLog.ERROR,"Cerrando fichero IO",e.getMessage());
                }
                if (conn!=null) conn.disconnect();
            }
        }
    }
}
