package es.upvmaster.fullmediaplayer;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
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.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;

import org.json.JSONArray;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;

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


public class ListarListas extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, PopupMenu.OnMenuItemClickListener {

    private AdaptadorListas adaptadorListas;
    private Activity activity;

    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;

    private InfoGlobal infoGlobal;

    static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";

    private MenuItem opcionPresionada = null;

    private int indiceLista = -1;

    static final int LISTA_QR = 1;
    static final int CREAR_LISTA = 2;

    private String idCarpeta;

    public static boolean actualizarListas = false;



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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarLista);
        toolbar.setTitle(R.string.app_name_listas);
        setSupportActionBar(toolbar);

        final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layoutLista);
        final 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);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popup = new PopupMenu(ListarListas.this,view, Gravity.BOTTOM);
                popup.setOnMenuItemClickListener(ListarListas.this);
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.menu_fab_listar_lista, popup.getMenu());
                popup.show();
            }
        });

        infoGlobal = InfoGlobal.getINSTANCIA();
        infoGlobal.inicializa(getApplicationContext());

        adaptadorListas = infoGlobal.getAdaptadorListaListas();

        adaptadorListas.setOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AdaptadorListas.ViewHolder viewHolder = (AdaptadorListas.ViewHolder) recyclerView.getChildViewHolder(view);
                indiceLista = viewHolder.getAdapterPosition();

                SharedPreferences prefs = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
                boolean controlParentalActivado = prefs.getBoolean("controlParentalActivado",false);
                if (controlParentalActivado && infoGlobal.getVectorListaListas().get(indiceLista).getParental()) {
                    crearDialogoControlParental().show();
                } else {
                    Intent intent = new Intent(ListarListas.this, ListarMedios.class);
                    intent.putExtra("IndiceLista", indiceLista);
                    startActivity(intent);
                }

            }
        });

        adaptadorListas.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                AdaptadorListas.ViewHolder viewHolder = (AdaptadorListas.ViewHolder) recyclerView.getChildViewHolder(view);
                indiceLista = viewHolder.getAdapterPosition();
                PopupMenu popup = new PopupMenu(ListarListas.this,view, Gravity.BOTTOM);
                popup.setOnMenuItemClickListener(ListarListas.this);
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.menu_item_listar_lista, popup.getMenu());
                popup.show();
                return false;
            }
        });

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_lista_listas);
        recyclerView.setAdapter(InfoGlobal.getINSTANCIA().getAdaptadorListaListas());
        layoutManager = new LinearLayoutManager(this); //Crear un layout de tipo Lineal
        recyclerView.setLayoutManager(layoutManager);

        if (InfoGlobal.getINSTANCIA().getVectorListaListas().size()==0) {
            new ObtenerListas().execute();
            actualizarListas = false;
        } else {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            boolean autoSincronizacion = prefs.getBoolean("p_autoSincronizacion",false);
            if (autoSincronizacion) {
                new Sincronizar(null).execute();
                actualizarListas = false;
            }
        }

    }

    @Override
    protected void onResume() {
        if (actualizarListas) {
            new ObtenerListas().execute();
            actualizarListas = false;
        } else
            InfoGlobal.getINSTANCIA().getAdaptadorListaListas().notifyDataSetChanged();
        super.onResume();
    }

    @Override
    protected void onRestart() {
       if (actualizarListas) {
            new ObtenerListas().execute();
            actualizarListas = false;
        } else
            InfoGlobal.getINSTANCIA().getAdaptadorListaListas().notifyDataSetChanged();
        super.onRestart();
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Dialog dialog = null;
        switch (item.getItemId()) {
            case R.id.menu_crearListaMedios:
                Intent intent = new Intent(this,CrearListasMedios.class);
                startActivityForResult(intent,CREAR_LISTA);
                break;
            case R.id.menu_eliminarListaMedios:
                dialog = crearDialogoEliminar(-1);
                dialog.show();
                break;
            case R.id.menu_recargarListaMedios:
                new ObtenerListas().execute();
                break;
            case R.id.menu_sincronizarListas:
                new Sincronizar(null).execute();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public AlertDialog crearDialogoControlParental() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        LayoutInflater inflater = this.getLayoutInflater();

        View v = inflater.inflate(R.layout.dialog_parental, null);
        TextView textoTitulo = (TextView) v.findViewById(R.id.text_titulo);
        final EditText pinParental = (EditText) v.findViewById(R.id.pin_parental);
        Button botonAceptar = (Button) v.findViewById(R.id.boton_aceptar);
        Button botonCancelar = (Button) v.findViewById(R.id.boton_cancelar);

        textoTitulo.setText(getResources().getString(R.string.lista_adultos));
        botonAceptar.setText(getResources().getString(R.string.aceptar));


        builder.setView(v);
        final AlertDialog alertDialog = builder.create();
        alertDialog.setCancelable(false);

        botonAceptar.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String pin = pinParental.getText().toString();
                        if (esNumericoCorrecto(pin,4)){
                            SharedPreferences prefs = getSharedPreferences("Preferencias", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = prefs.edit();
                            String controlParentalPin = prefs.getString("controlParentalPin","");
                            if (controlParentalPin.equals(pin)) {
                                alertDialog.dismiss();
                                Intent intent = new Intent(ListarListas.this, ListarMedios.class);
                                intent.putExtra("IndiceLista", indiceLista);
                                startActivity(intent);
                            } else {
                                mostrarMensaje(ListarListas.this,getResources().getString(R.string.pin_incorrecto));
                            }
                        }
                        else {
                            mostrarMensaje(ListarListas.this,getResources().getString(R.string.formato_pin_incorrecto));
                        }
                    }
                }
        );

        botonCancelar.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                }

        );


        return alertDialog;
    }

    private AlertDialog crearDialogoEliminar(final int indice) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        if (indice==-1) {

            builder.setTitle(getResources().getString(R.string.eliminar_listas))
                    .setMessage(getResources().getString(R.string.estas_seguro_eliminar_listas))
                    .setPositiveButton(getResources().getString(R.string.si),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    boolean actualizar = false;
                                    for (int i = InfoGlobal.getINSTANCIA().getVectorListaListas().size() - 1; i >= 0; i--) {
                                        actualizar = InfoGlobal.getINSTANCIA().eliminarListaMedios(i, false) || actualizar;
                                    }
                                    if (actualizar) adaptadorListas.notifyDataSetChanged();
                                }
                            })
                    .setNegativeButton(getResources().getString(R.string.no),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
        } else {
            builder.setTitle(getResources().getString(R.string.eliminar_lista))
                    .setMessage(getResources().getString(R.string.estas_seguro_eliminar_lista))
                    .setPositiveButton(getResources().getString(R.string.si),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    boolean actualizar = InfoGlobal.getINSTANCIA().eliminarListaMedios(indice,true);
                                    if (actualizar) adaptadorListas.notifyDataSetChanged();
                                }
                            })
                    .setNegativeButton(getResources().getString(R.string.no),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
        }

        return builder.create();
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Intent intent;
        opcionPresionada = item;
        switch (item.getItemId()) {
            case R.id.nav_listaMedio:
                break;
            case R.id.nav_localVideo:
                intent = new Intent(ListarListas.this,ListarVideos.class);
                startActivity(intent);
                break;
            case R.id.nav_localAudio:
                intent = new Intent(ListarListas.this,ListarAudios.class);
                startActivity(intent);
                break;
            case R.id.nav_archivoMedio:
                intent = new Intent(ListarListas.this,ListarArchivos.class);
                startActivity(intent);
                break;
            case R.id.nav_urlMedio:
                intent = new Intent(ListarListas.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_layoutLista);
        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

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

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Dialog dialog;
        Intent compartirInformacion = null;
        switch (item.getItemId()) {
            case R.id.fab_incorporarListaURL:
                dialog = crearDialogoURL(ElementosValidos.LISTA);
                dialog.show();
                return true;
            case R.id.fab_incorporarListaQR:
                try {
                   Intent intent = new Intent(ACTION_SCAN);
                    intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                    startActivityForResult(intent, LISTA_QR);
                } catch (ActivityNotFoundException e) {
                    dialog = crearDialogoBarcode();
                    dialog.show();
                }
                return true;
            case R.id.item_eliminarLista:
                dialog = crearDialogoEliminar(indiceLista);
                dialog.show();
                return true;
            case R.id.item_compartirLink:
                compartirInformacion = new Intent();
                compartirInformacion.setAction(Intent.ACTION_SEND);
                compartirInformacion.putExtra(Intent.EXTRA_TEXT,InfoGlobal.getINSTANCIA().getVectorListaListas().get(indiceLista).getUrl());
                compartirInformacion.setType("text/plain");
                startActivity(Intent.createChooser(compartirInformacion,getResources().getString(R.string.compartir_link)));
                return true;
            case R.id.item_compartirLista:
                compartirInformacion = new Intent();
                compartirInformacion.setAction(Intent.ACTION_SEND);
                Uri fichero = Uri.parse("file://" + InfoGlobal.getINSTANCIA().getDirectorio().getAbsolutePath() + File.separator + InfoGlobal.getINSTANCIA().getVectorListaListas().get(indiceLista).getNameFile());
                compartirInformacion.putExtra(Intent.EXTRA_STREAM, fichero);
                compartirInformacion.setType("text/plain");
                startActivity(Intent.createChooser(compartirInformacion,getResources().getString(R.string.compartir_lista)));
                return true;
            case R.id.item_sincronizarLista:
                new Sincronizar(adaptadorListas.vectorListaMedios.get(indiceLista).getUrl()).execute();
                return true;
            default:
                return false;
        }
    }

    private AlertDialog crearDialogoBarcode() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(getResources().getString(R.string.barcode_no_instalado))
                .setMessage(getResources().getString(R.string.descargar_app))
                .setPositiveButton(getResources().getString(R.string.si),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                try {
                                    startActivity(intent);
                                } catch (ActivityNotFoundException e) {

                                }
                            }
                        })
                .setNegativeButton(getResources().getString(R.string.no),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });

        return builder.create();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case LISTA_QR:
                if (resultCode == RESULT_OK) {
                    String urlString = intent.getStringExtra("SCAN_RESULT");
                    String formato = intent.getStringExtra("SCAN_RESULT_FORMAT");
                    if (formato.equals("QR_CODE"))
                        new DescargarLista(urlString).execute();
                }
                break;
            case CREAR_LISTA:
                if (resultCode == RESULT_OK) {
                    new ObtenerListas().execute();
                }
        }
    }

    class ObtenerListas extends AsyncTask<Void, Void, Void> {
        private ProgressDialog pDialog;
        private Vector<ListaMedios> listasMedios;
        private ListaMedios listaMedios;
        private JSONArray lista_medios_json;
        private Context context;

        FilenameFilter fileNameFilter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if(name.lastIndexOf('.')>0)
                {
                    int lastIndex = name.lastIndexOf('.');
                    String extension = name.substring(lastIndex);

                    if(extension.equals(".w3u")) return true;
                }
                return false;
            }
        };

        public ObtenerListas() {
            this.listasMedios = InfoGlobal.getINSTANCIA().getVectorListaListas();
            this.context = InfoGlobal.getINSTANCIA().getContextoAplicacion();
        }


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

        @Override
        protected Void doInBackground(Void... arg0) {
            listasMedios.clear();

            File[] ficherosJSON = InfoGlobal.getINSTANCIA().getDirectorio().listFiles(fileNameFilter);

            for (File fichero : ficherosJSON) {
                JSONParser sh = new JSONParser();
                String jsonStr = sh.makeServiceCall(fichero);
                if (jsonStr != null) {
                    Gson gson = new Gson();
                    ListaMedios listaMediosAuxiliar;
                    try {
                        listaMediosAuxiliar = gson.fromJson(jsonStr, ListaMedios.class);
                    } catch (Exception e) {
                        listaMediosAuxiliar = null;
                    }
                    if (listaMediosAuxiliar!=null) {
                        listaMedios = new ListaMedios();
                        listaMedios.setName(listaMediosAuxiliar.getName());
                        listaMedios.setAuthor(listaMediosAuxiliar.getAuthor());
                        listaMedios.setUrl(listaMediosAuxiliar.getUrl());
                        listaMedios.setNameFile(fichero.getName());
                        listaMedios.setParental(listaMediosAuxiliar.getParental());
                        listaMedios.setInfo(listaMediosAuxiliar.getInfo());
                        listasMedios.add(listaMedios);
                    }
                } else {
                    imprimirLog(Libreria.TipoLog.DEBUG,"Service Handler", "Esta habiendo problemas para cargar el JSON");
                }

            }

            return null;
        }

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

            adaptadorListas.notifyDataSetChanged();
        }
    }

    public AlertDialog crearDialogoURL(final ElementosValidos elemento) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        LayoutInflater inflater = this.getLayoutInflater();

        View v = inflater.inflate(R.layout.dialog_medio_url, null);
        TextView textView = (TextView) v.findViewById(R.id.info_text_url);
        if (elemento == ElementosValidos.MEDIO)
            textView.setText(getResources().getString(R.string.info_text_url));
        else
            textView.setText(getResources().getString(R.string.info_text_list_url));

        builder.setView(v);
        final AlertDialog alertDialog = builder.create();

        Button botonAceptar = (Button) v.findViewById(R.id.boton_aceptar);
        Button botonCancelar = (Button) v.findViewById(R.id.boton_cancelar);
        final EditText urlInput = (EditText) v.findViewById(R.id.url_input);

        botonAceptar.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                        String url = urlInput.getText().toString().trim();
                        if (url.length()<0) {
                            mostrarMensaje(ListarListas.this,getResources().getString(R.string.url_incorrecta));
                        } else {
                            if (elemento == ElementosValidos.MEDIO)
                                new ComprobarAccesoMedio(url).execute();
                            else
                                new DescargarLista(url).execute();
                        }
                    }
                }
        );

        botonCancelar.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                        mostrarMensaje(ListarListas.this,getResources().getString(R.string.operacion_cancelada));
                    }
                }

        );
        return alertDialog;
    }

    private void iniciarMedio(boolean resultado, String url) {
        if (resultado) {
            Intent intent = new Intent(ListarListas.this, ReproductorWeb.class);
            intent.putExtra("Tipo", "URL");
            intent.putExtra("Ruta", url);
            startActivity(intent);
        } else {
            mostrarMensaje(ListarListas.this,getResources().getString(R.string.medio_no_accesible));
        }
    }

    class ComprobarAccesoMedio extends AsyncTask<Void, Void, Boolean> {
        private String urlString;
        private ProgressDialog pDialog;

        public ComprobarAccesoMedio(String urlString) {
            this.urlString = urlString;
        }

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

        @Override
        protected Boolean doInBackground(Void... arg0) {
            boolean accesible = false;
            try {
                URL url = new URL(urlString);
                HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                huc.setRequestMethod("HEAD");
                int codigoRespuesta=huc.getResponseCode();
                accesible = codigoRespuesta != 404;
                huc.disconnect();
            } catch (Exception e) {
                imprimirLog(TipoLog.ERROR,"Comprobando medio",e.getMessage());
            }
            return accesible;
        }

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

    class DescargarLista extends AsyncTask<Void, Void, Boolean> {
        private String urlString;
        private ProgressDialog pDialog;

        public DescargarLista(String urlString) {
            if (urlString.indexOf("pastebin.com/")>0 && urlString.indexOf("raw")<0)
                urlString = urlString.replace("pastebin.com/","pastebin.com/raw/");

            this.urlString = urlString;
        }

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

        @Override
        protected Boolean doInBackground(Void... arg0) {
            boolean accesible = false;
            File file = null;
            URL url = null;
            HttpURLConnection huc = null;
            int posCaracter;
            String nombreFichero;
            FileOutputStream fileOutput = null;

            try {
                url = new URL(urlString);
                huc = (HttpURLConnection) url.openConnection();
                accesible = true;
                if (accesible) {
                    posCaracter = urlString.lastIndexOf("?");
                    if (posCaracter<0) posCaracter = urlString.length();
                    nombreFichero = urlString.substring(urlString.lastIndexOf("/")+1,posCaracter);
                    posCaracter = nombreFichero.lastIndexOf(".");
                    if (posCaracter>0) nombreFichero = nombreFichero.substring(0,posCaracter);
                    nombreFichero += ".w3u";
                    try {
                        file = new File(InfoGlobal.getINSTANCIA().getDirectorio(),nombreFichero);

                        huc.setRequestMethod("GET");
                        huc.setDoOutput(false);
                        InputStream inputStream = huc.getInputStream();
                        fileOutput = new FileOutputStream(file);

                        int downloadedSize = 0;
                        byte[] buffer = new byte[1024];
                        int bufferLength = 0;
                        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                            fileOutput.write(buffer, 0, bufferLength);
                            downloadedSize += bufferLength;
                        }
                    } catch (MalformedURLException e) {
                        imprimirLog(TipoLog.ERROR,"Descargando lista",e.getMessage());
                        accesible = false;
                    } catch (IOException e) {
                        imprimirLog(TipoLog.ERROR,"Descargando lista IO",e.getMessage());
                        accesible = false;
                    } catch (Exception e) {
                        imprimirLog(TipoLog.ERROR,"Descargando lista",e.getMessage());
                        accesible = false;
                    } finally {
                        try {
                            if (fileOutput != null) fileOutput.close();
                            else if (file.exists() && file.length()==0) {
                                file.delete();
                                accesible = false;
                            }
                        } catch (IOException e) {
                            imprimirLog(TipoLog.ERROR,"Cerrando fichero IO",e.getMessage());
                        }
                    }
                }
                huc.disconnect();
            } catch (Exception e) {
                imprimirLog(TipoLog.ERROR,"Descargando lista",e.getMessage());
            }
            return accesible;
        }

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

            if (result) new ObtenerListas().execute();
            else {
                mostrarMensaje(ListarListas.this,getResources().getString(R.string.fallo_cargando_lista));
            }
        }
    }

    class Sincronizar extends AsyncTask<Void, Void, Boolean> {
        private String urlString;
        private ProgressDialog pDialog;

        public Sincronizar(String urlString) {
            if (urlString!=null)
                this.urlString = urlString;
        }

        private String ajustarURL(String urlString) {
            if (urlString.indexOf("pastebin.com/")>0 && urlString.indexOf("raw")<0)
                return urlString.replace("pastebin.com/","pastebin.com/raw/");
            else
                return urlString;
        }

        private boolean sincronizarLista(String urlFichero) {
            boolean sincronizado = true;
            File file = null;
            URL url = null;
            HttpURLConnection huc = null;
            int posCaracter;
            String nombreFichero;
            FileOutputStream fileOutput = null;
            try {
                url = new URL(ajustarURL(urlFichero));
                huc = (HttpURLConnection) url.openConnection();
                posCaracter = urlFichero.lastIndexOf("?");
                if (posCaracter<0) posCaracter = urlFichero.length();
                nombreFichero = urlFichero.substring(urlFichero.lastIndexOf("/")+1,posCaracter);
                posCaracter = nombreFichero.lastIndexOf(".");
                if (posCaracter>0) nombreFichero = nombreFichero.substring(0,posCaracter);
                nombreFichero += ".w3u";
                try {
                    file = new File(InfoGlobal.getINSTANCIA().getDirectorio(),nombreFichero);

                    huc.setRequestMethod("GET");
                    huc.setDoOutput(false);
                    InputStream inputStream = huc.getInputStream();
                    fileOutput = new FileOutputStream(file);

                    int downloadedSize = 0;
                    byte[] buffer = new byte[1024];
                    int bufferLength = 0;
                    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                        fileOutput.write(buffer, 0, bufferLength);
                        downloadedSize += bufferLength;
                    }
                } catch (MalformedURLException e) {
                    imprimirLog(TipoLog.ERROR,"Sincronizando lista",e.getMessage());
                    sincronizado = false;
                } catch (IOException e) {
                    imprimirLog(TipoLog.ERROR,"Sincronizando lista IO",e.getMessage());
                    sincronizado = false;
                } catch (Exception e) {
                    imprimirLog(TipoLog.ERROR,"Sincronizando lista",e.getMessage());
                    sincronizado = false;
                } finally {
                    try {
                        if (fileOutput != null) fileOutput.close();
                        else if (file.exists() && file.length()==0) {
                            file.delete();
                            sincronizado = false;
                        }
                    } catch (IOException e) {
                        imprimirLog(TipoLog.ERROR,"Cerrando fichero IO",e.getMessage());
                    }
                }

                huc.disconnect();
            } catch (Exception e) {
                imprimirLog(TipoLog.ERROR,"Sincronizando lista",e.getMessage());
            }
            return sincronizado;
        }

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

        @Override
        protected Boolean doInBackground(Void... arg0) {
            boolean sincronizado = false;
            if (urlString!=null) sincronizado = sincronizarLista(urlString);
            else {
                for (int i=0;i<infoGlobal.getVectorListaListas().size();i++) {
                    if (infoGlobal.getVectorListaListas().get(i).getUrl().length()>0)
                        sincronizado = sincronizarLista(infoGlobal.getVectorListaListas().get(i).getUrl()) || sincronizado;
                }
            }
            return sincronizado;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (pDialog.isShowing()){
                pDialog.dismiss();
            }
            if (result) new ObtenerListas().execute();
            else {
                mostrarMensaje(ListarListas.this,getResources().getString(R.string.fallo_sincronizando_lista));
            }
        }
    }
}
