package academic.th;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

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;

import academic.th.mMySQL.Downloader;

public class NotasActivity extends AppCompatActivity implements View.OnClickListener{


    //final static String urlAddress="http://lasalle.fin.ec/zacciones/obtener_trimestres.php";
    String codigo_alu = "";
    String nombre_tri="";
    ///para consulta
    Button consultarNotas;
    TextView resultadoNotas;


    ///Urls
    String ip = "http://lasalle.fin.ec/zacciones";
    String consultar_trimestre_id = ip + "/obtener_trimestres_por_id.php";
    String respuesta;
    ObtenerWebService2 hiloconexion;
    ObtenerWebService2 hiloconexion2;


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_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();
            }
        });


        //////////  para consulta notas  ///////

        consultarNotas = (Button) findViewById(R.id.Btnconsultanotas);
        //idalumno=(EditText)findViewById(R.id.editcalumnobd);
        resultadoNotas = (TextView) findViewById(R.id.resultadonotas);


        consultarNotas.setOnClickListener(this);


        ////////////// CONSULTA PARAMETROS SQLITE

        AdminSQLite admin = new AdminSQLite(this, "administracion4", null, 1);
        SQLiteDatabase bd = admin.getWritableDatabase();
        //String sclaumno1=calumno1.getText().toString();

        Cursor fila = bd.rawQuery("select calumno_alu,cpadre_alu,colegio_alu from alumno", null);

        if (fila.moveToFirst()) {

            codigo_alu = fila.getString(0);


        } else {

            Toast.makeText(this, "El Alumno No esta ingresado", Toast.LENGTH_SHORT).show();
            bd.close();
        }

        //////  PARA LLENAR EL SPINNER  /////////
        String urlAddress = "http://lasalle.fin.ec/zacciones/obtener_trimestres.php?codigo_alu=" + codigo_alu.toString();

        Spinner spinertrimestre = (Spinner) findViewById(R.id.spinnerTrimestre1);
        new Downloader(NotasActivity.this, urlAddress, spinertrimestre).execute();



        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }


    @Override
    public void onClick(View v) {


        switch (v.getId()) {

            case R.id.Btnconsultanotas:
                hiloconexion = new ObtenerWebService2();

               //////////  Consulta trimestre escojido spinner  /////////
                AdminSQLite admin = new AdminSQLite(this, "administracion4", null, 1);
                SQLiteDatabase bd = admin.getWritableDatabase();
                //String sclaumno1=calumno1.getText().toString();

                Cursor fila = bd.rawQuery("select v1_par from parametros", null);

                if (fila.moveToFirst()) {

                    nombre_tri = fila.getString(0);


                } else {

                    Toast.makeText(this, "Error Trimestre escojido", Toast.LENGTH_SHORT).show();
                    bd.close();
                }

                nombre_tri=nombre_tri.replace(" ","/x");//// PARA TRAER LOS PARCIALES

                String cadenaauxiliar = consultar_trimestre_id + "?idtrimestre="+nombre_tri+"&codigo_alu="+codigo_alu.toString();
                //Toast.makeText(this, idalumno.getText().toString(), Toast.LENGTH_SHORT).show();
                hiloconexion.execute(cadenaauxiliar, "2");


            default:
                break;
        }
    }



    /////   ****** obtener webservice  ******* //////////

    public class ObtenerWebService2 extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            resultadoNotas.setText("");
            super.onPreExecute();

        }

        @Override
        protected void onPostExecute(String s) {
            resultadoNotas.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("nombre_mat") + " :  " +
                                       // alumnosJSON.getJSONObject(i).getString("nombre_tri") + " " +
                                        alumnosJSON.getJSONObject(i).getString("nombre_prc") + " :  " +
                                        alumnosJSON.getJSONObject(i).getString("nota_prccri") + "\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 = result.toString();
                        }

                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return devuelve;


            }


            return null;
        }
    }



}
