package es.upvmaster.fullmediaplayer;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Vector;

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

public class ListarVideos extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private AdaptadorMedios adaptadorVideos;
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private static ListaMedios listaVideos;

    private MenuItem opcionPresionada = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listar_videos);

        this.listaVideos = new ListaMedios();
        this.listaVideos.setName(getResources().getString(R.string.app_name_videos));
        this.listaVideos.setAuthor("");
        InfoGlobal.getINSTANCIA().agregarMedios(this.listaVideos.getStations());
        adaptadorVideos = InfoGlobal.getINSTANCIA().getAdaptadorMedio();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarVideo);
        toolbar.setTitle(R.string.app_name_videos);
        setSupportActionBar(toolbar);

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layoutVideo);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
        drawerLayout.setDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                if (opcionPresionada!=null) opcionPresionada.setChecked(false);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        adaptadorVideos.setOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdaptadorMedios.ViewHolder viewHolder = (AdaptadorMedios.ViewHolder) recyclerView.getChildViewHolder(v);
                Medio medio = InfoGlobal.getINSTANCIA().getVectorMedios().get(viewHolder.getAdapterPosition());
                File file = new File(medio.getUrl());
                if (file.exists()) {
                    iniciarReproduccion(ListarVideos.this,TipoMedio.LOCAL,medio.getUrl());
                }
            }
        });

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_lista_videos);
        recyclerView.setAdapter(adaptadorVideos);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            layoutManager = new StaggeredGridLayoutManager(4,  StaggeredGridLayoutManager.VERTICAL);
        }
        else {
            layoutManager = new StaggeredGridLayoutManager(2,  StaggeredGridLayoutManager.VERTICAL);
        }
        layoutManager.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!listaVideos.mediosCargados())
            new ObtenerVideos().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_listar_video, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_recargarVideos:
                new ObtenerVideos().execute();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Intent intent;
        opcionPresionada = item;
        switch (item.getItemId()) {
            case R.id.nav_listaMedio:
                intent = new Intent(ListarVideos.this,ListarListas.class);
                startActivity(intent);
                break;
            case R.id.nav_localVideo:
                new ObtenerVideos().execute();
                break;
            case R.id.nav_localAudio:
                intent = new Intent(ListarVideos.this,ListarAudios.class);
                startActivity(intent);
                break;
            case R.id.nav_archivoMedio:
                intent = new Intent(ListarVideos.this,ListarArchivos.class);
                startActivity(intent);
                break;
            case R.id.nav_urlMedio:
                intent = new Intent(ListarVideos.this,AccederMedioURL.class);
                startActivity(intent);
                break;
            case R.id.nav_preferencias:
                Intent intentPref = new Intent(this, Preferencias.class);
                startActivity(intentPref);
                break;
            case R.id.nav_salir:
                Intent intentSalir = new Intent(Intent.ACTION_MAIN);
                intentSalir.addCategory(Intent.CATEGORY_HOME);
                intentSalir.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intentSalir);
        }

        DrawerLayout drawerLayout = (DrawerLayout) findViewById( R.id.drawer_layoutVideo);
        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawerLayout = (DrawerLayout) findViewById( R.id.drawer_layoutVideo);
        if (drawerLayout.isDrawerOpen(GravityCompat.START))
        {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    class ObtenerVideos extends AsyncTask<Void, Void, Boolean> {
        private ProgressDialog pDialog;
        private Vector<Medio> stations;
        private boolean operacionCancelada = false;

        public ObtenerVideos() {
            stations = new Vector<Medio>();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ListarVideos.this);
            pDialog.setMessage(getResources().getString(R.string.obteniendo_videos));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    operacionCancelada = true;
                    ObtenerVideos.this.cancel(true);
                }
            });
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            Medio medio;
            try {
                int video_column_index;
                String[] proj = {
                        MediaStore.Video.Media._ID,
                        MediaStore.Video.Media.DATA,
                        MediaStore.Video.Media.DISPLAY_NAME};

                Cursor videocursor = getContentResolver().query(
                        MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                        proj,
                        null,
                        null,
                        MediaStore.Video.Media.DISPLAY_NAME);

                int count = videocursor.getCount();

                for (int i = 0; i < count; i++) {
                    if (!operacionCancelada) {
                        medio = new Medio();

                        videocursor.moveToPosition(i);

                        video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
                        String name = videocursor.getString(video_column_index);
                        medio.setName(name);

                        video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                        String filepath = videocursor.getString(video_column_index);
                        medio.setUrl(filepath);

                        medio.setImage(generarImagen(medio.getUrl()));

                        stations.add(medio);
                    } else break;
                }
                videocursor.close();
                if (!operacionCancelada)
                    adaptadorVideos.vectorMedios=stations;

            } catch (Exception e) {
                imprimirLog(TipoLog.ERROR,"Recuperando videos",e.getMessage());
                return false;
            }
            return true;
        }

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

            if (result)
                adaptadorVideos.notifyDataSetChanged();
            else
                mostrarMensaje(ListarVideos.this,getResources().getString(R.string.error_recuperando_videos));
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            finalizarActividad();
        }

        private String generarImagen(String url) {
            String rutaImagen = url.substring(0,url.lastIndexOf(".")+1) + "jpg";
            File fileImagen = new File(InfoGlobal.getINSTANCIA().getDirectorio() + rutaImagen.substring(rutaImagen.lastIndexOf("/")));
            FileOutputStream fileOutputStream = null;
            if (!fileImagen.exists()) {
                Bitmap bmThumbnail = ThumbnailUtils.extractThumbnail(
                        ThumbnailUtils.createVideoThumbnail(
                                url,
                                MediaStore.Video.Thumbnails.MINI_KIND
                        ),
                        80,
                        50);
                try {
                    fileOutputStream = new FileOutputStream(fileImagen);
                    bmThumbnail.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
                    fileOutputStream.close();
                } catch (Exception e) {
                    imprimirLog(TipoLog.ERROR,"Guardando bitmap", e.getMessage());
                }
            }

            if (fileImagen.exists())
                return fileImagen.getAbsolutePath();
            else
                return "";
        }
    }

    private void finalizarActividad() {
        finish();
    }
}
