package es.upvmaster.fullmediaplayer;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.net.HttpURLConnection;
import java.net.URL;

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

public class AccederMedioURL extends AppCompatActivity {

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

    private void iniciarMedio(boolean resultado, String url) {
        if (resultado) {
            iniciarReproduccion(AccederMedioURL.this,TipoMedio.URL,url);
        } else {
            mostrarMensaje(AccederMedioURL.this,getResources().getString(R.string.medio_no_accesible));
        }
        finish();
    }

    public AlertDialog crearDialogoURL() {
        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);
        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);

        textView.setText(getText(R.string.info_text_url).toString());
        textView.setTextColor(Color.rgb(0,0,0));
        botonAceptar.setText(getResources().getString(R.string.aceptar));
        botonCancelar.setText(getResources().getString(R.string.cancelar));

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

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

                }
            }
        );

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

        );


        return alertDialog;
    }

    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(AccederMedioURL.this);
            pDialog.setMessage(InfoGlobal.getINSTANCIA().getContextoAplicacion().getResources().getString(R.string.comprobando_url));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    ComprobarAccesoMedio.this.cancel(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 ex) {
                imprimirLog(TipoLog.ERROR,getResources().getString(R.string.comprobando_medio),ex.getMessage());
            }
            return accesible;
        }

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

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

}
