package es.upvmaster.fullmediaplayer;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.FileList;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

import static es.upvmaster.fullmediaplayer.Libreria.*;

public class SeguridadRestaurar extends AppCompatActivity {
    private String idCarpeta;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        recuperarCopiaSeguridad();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case SOLICITUD_SELECCION_CUENTA:
                if (resultCode == RESULT_OK && intent != null && intent.getExtras() != null) {
                    nombreCuenta = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    if (nombreCuenta != null) {
                        credencial.setSelectedAccountName(nombreCuenta);
                        servicio = obtenerServicioDrive(credencial);

                        SharedPreferences prefs = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putString("nombreCuenta", nombreCuenta);
                        editor.commit();

                        new CrearCarpetaEnDrive().execute();
                    }
                }
                break;
            case SOLICITUD_AUTORIZACION:
                if (resultCode == Activity.RESULT_OK) {
                    new CrearCarpetaEnDrive().execute();
                } else {
                    mostrarMensaje(SeguridadRestaurar.this, getResources().getString(R.string.usuario_no_autoriza_google));
                }
                break;
        }
    }

    private void recuperarCopiaSeguridad() {
        if (!comprobarGooglePlayServices()) {
            mostrarMensaje(SeguridadRestaurar.this,getResources().getString(R.string.error_google_play));
            return;
        }

        if (credencial == null)
            credencial = GoogleAccountCredential.usingOAuth2(SeguridadRestaurar.this, Arrays.asList(DriveScopes.DRIVE));


        SharedPreferences prefs = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
        nombreCuenta = prefs.getString("nombreCuenta", null);

        if (nombreCuenta != null) {
            credencial.setSelectedAccountName(nombreCuenta);
            servicio = obtenerServicioDrive(credencial);
            new CrearCarpetaEnDrive().execute();
        } else {
            startActivityForResult(credencial.newChooseAccountIntent(), SOLICITUD_SELECCION_CUENTA);
        }
    }

    private void iniciarRecuperarCopiaSeguridad() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                mostrarCarga(SeguridadRestaurar.this,getResources().getString(R.string.realizandor_restauracion));
                String ruta;
                FileOutputStream fileOutput = null;
                File ficheroLocal = null;

                try {
                    FileList listadoCompleto;
                    listadoCompleto = servicio.files().list()
                            .setQ("'" + idCarpeta + "' in parents and trashed = false")
                            .execute();
                    for (com.google.api.services.drive.model.File ficheroDrive : listadoCompleto.getItems()) {
                        if (ficheroDrive.getDownloadUrl()!=null && ficheroDrive.getDownloadUrl().length()>0) {
                            try {

                                ruta = Environment.getExternalStorageDirectory().toString() + File.separator + "FullMediaPlayer" + File.separator + ficheroDrive.getTitle();
                                ficheroLocal = new File(ruta);
                                fileOutput = new FileOutputStream(ficheroLocal);

                                String fileId = ficheroDrive.getId();
                                OutputStream outputStream = fileOutput;
                                servicio.files().get(fileId).setAlt("media").executeAndDownloadTo(outputStream);


                                fileOutput.close();
                            } catch (IOException e) {
                                imprimirLog(Libreria.TipoLog.ERROR,"Restaurando copia",e.getMessage());
                            } finally {
                                try {
                                    if (fileOutput != null) fileOutput.close();
                                    else if (ficheroLocal.exists() && ficheroLocal.length()==0) {
                                        ficheroLocal.delete();
                                    }
                                } catch (IOException e) {
                                    imprimirLog(Libreria.TipoLog.ERROR,"Cerrando fichero",e.getMessage());
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    mostrarMensaje(SeguridadRestaurar.this,getResources().getString(R.string.error_restaurando));
                } finally {
                    ocultarCarga(SeguridadRestaurar.this);
                    finish();
                }

                ListarListas.actualizarListas = true;
            }
        });
        t.start();

    }

    private boolean comprobarGooglePlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                finish();
            }
            return false;
        }
        return true;
    }

    private Drive obtenerServicioDrive(GoogleAccountCredential credential) {
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credencial).build();
    }

    class CrearCarpetaEnDrive extends AsyncTask<Void, Void, Boolean> {
        private ProgressDialog pDialog;

        public CrearCarpetaEnDrive() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(SeguridadRestaurar.this);
            pDialog.setMessage(getResources().getString(R.string.comprobando_carpeta_drive));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            boolean existe = false;
            com.google.api.services.drive.model.File carpetaDrive = null;
            try {
                com.google.api.services.drive.model.File carpetaNueva = new com.google.api.services.drive.model.File();  //Representa el fichero de tipo carpeta
                carpetaNueva.setTitle("FullMediaPlayer"); //Nombre de la carpeta
                carpetaNueva.setMimeType("application/vnd.google-apps.folder"); //Indicar que es un fichero de tipo carpeta

                FileList listadoCarpetas = servicio.files()
                        .list()
                        .setQ("title = 'FullMediaPlayer' and mimeType = 'application/vnd.google-apps.folder'")
                        .execute();
                if (listadoCarpetas.size()>0) {
                    for (com.google.api.services.drive.model.File carpeta : listadoCarpetas.getItems()) {
                        if (idCarpeta==null && carpeta.getExplicitlyTrashed() == false) {
                            idCarpeta = carpeta.getId();
                            existe = true;
                        } else {
                            servicio.files().delete(carpeta.getId()).execute();
                        }
                    }

                }

                if (!existe) {
                    carpetaDrive = servicio.files().insert(carpetaNueva).execute();
                    if (carpetaDrive != null) {
                        idCarpeta = carpetaDrive.getId();
                        existe = true;
                    }
                }

            } catch (UserRecoverableAuthIOException e) {
                startActivityForResult(e.getIntent(), SOLICITUD_AUTORIZACION);
            } catch (IOException e) {
                imprimirLog(Libreria.TipoLog.ERROR,"Crear carpeta IO",e.getMessage());
            } catch (Exception e) {
                imprimirLog(Libreria.TipoLog.ERROR,"Crear carpeta",e.getMessage());
            }

            return existe;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }

            if (result) iniciarRecuperarCopiaSeguridad();
            else finish();

        }
    }
}
