package academic.th;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class ConsultaNotasActivity extends AppCompatActivity implements View.OnClickListener {

    Button consultar;
    EditText idalumno;
    TextView resultado;



    ///Urls
    String ip="http://lasalle.fin.ec/zacciones";
    String consultar_por_id=ip+"/obtener_alumno_por_id.php";


    ObtenerWebService hiloconexion;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consulta_notas);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();


            }
        });

        consultar=(Button)findViewById(R.id.Btnconsultabd);
        idalumno=(EditText)findViewById(R.id.editcalumnobd);
        resultado=(TextView)findViewById(R.id.resultado);


        consultar.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {




        switch (v.getId()){

            case R.id.Btnconsultabd:
                hiloconexion= new ObtenerWebService();
                String cadenaauxiliar=consultar_por_id+"?idalumno="+idalumno.getText().toString();
                //Toast.makeText(this, idalumno.getText().toString(), Toast.LENGTH_SHORT).show();
                hiloconexion.execute(cadenaauxiliar,"2");


            default:
                break;
        }
    }


    public class ObtenerWebService extends AsyncTask<String,Void,String>{

        @Override
        protected void onPreExecute() {
            resultado.setText("");
            super.onPreExecute();

        }

        @Override
        protected void onPostExecute(String s) {
            resultado.setText(s);
            //super.onPostExecute(s);
        }

        @Override
        protected void onProgressUpdate(Void... values) {

            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled(String s) {
            super.onCancelled(s);
        }

        @Override
        protected String doInBackground(String... params) {

            String cadena=params[0];
            URL url=null;
            String devuelve="";



            if(params[1]=="2"){

                try {

                    url = new URL(cadena);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //Abrir la conexión
                    connection.setRequestProperty("User-Agent", "Mozilla/5.0" +
                            " (Linux; Android 19; es-ES) Ejemplo HTTP");
                    //connection.setHeader("content-type", "application/json");

                    int respuesta = connection.getResponseCode();
                    StringBuilder result = new StringBuilder();

                    if (respuesta == HttpURLConnection.HTTP_OK){


                        InputStream in = new BufferedInputStream(connection.getInputStream());  // preparo la cadena de entrada

                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));  // la introduzco en un BufferedReader

                        // El siguiente proceso lo hago porque el JSONOBject necesita un String y tengo
                        // que tranformar el BufferedReader a String. Esto lo hago a traves de un
                        // StringBuilder.

                        String line;
                        while ((line = reader.readLine()) != null) {
                            result.append(line);        // Paso toda la entrada al StringBuilder
                        }

                        //Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
                        JSONObject respuestaJSON = new JSONObject(result.toString());   //Creo un JSONObject a partir del StringBuilder pasado a cadena
                        //Accedemos al vector de resultados

                        String resultJSON = respuestaJSON.getString("estado");   // estado es el nombre del campo en el JSON

                        if (resultJSON.equals("1")){      // hay un alumno que mostrar

                            JSONArray alumnosJSON = respuestaJSON.getJSONArray("alumno");   // estado es el nombre del campo en el JSON
                            for(int i=0;i<=alumnosJSON.length() ;i++){
                                devuelve = devuelve + alumnosJSON.getJSONObject(i).getString("serial_alu") + " " +
                                        alumnosJSON.getJSONObject(i).getString("nombre_alu") + " " +
                                        alumnosJSON.getJSONObject(i).getString("apellido_alu") + "\n";

                            }


                            /*devuelve = devuelve + respuestaJSON.getJSONObject("alumno").getString("serial_alu") + " " +
                                    respuestaJSON.getJSONObject("alumno").getString("nombre_alu") + " " +
                                    respuestaJSON.getJSONObject("alumno").getString("apellido_alu") + "\n";  */

                        }
                        else if (resultJSON.equals("2")){
                            devuelve =" No hay alumnos";
                        }

                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return devuelve;


            }


            return null;
        }
    }
}
