package academic.th;

import android.content.Intent;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
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 InicioActivity extends AppCompatActivity implements View.OnClickListener {

    Button botonregistrar;
    String codigo_alu="";
    String basedatos="";
    TextView nombrealumno;
    TextView cursoalumno;

    ///Urls
    String ip = "http://lasalle.fin.ec/zacciones";
    String consultar_nombrealumno_id = ip + "/obtener_nombrealumno_por_id.php";
    String respuesta;
    ObtenerWebService4 hiloconexion;

    String consultar_cursoalumno_id = ip + "/obtener_cursoalumno_por_id.php";
    ObtenerWebService5 hiloconexion5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inicio);
        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();
            }
        });

        botonregistrar=(Button) findViewById(R.id.button2);
        botonregistrar.setOnClickListener(this);
        nombrealumno=(TextView)findViewById(R.id.textViewAlumnoInicio);
        cursoalumno=(TextView)findViewById(R.id.textViewCursoAlumno);


        ////// PARA TRAER EL NOMBRE DEL ALUMNO REGISTRADO /////
        AdminSQLite admin = new AdminSQLite(this,"administracion4",null,1);
        SQLiteDatabase bd= admin.getWritableDatabase();

        Cursor fila=bd.rawQuery("select calumno_alu,cpadre_alu,colegio_alu from alumno",null);

        if(fila.moveToFirst()){

            codigo_alu= fila.getString(0);
            basedatos= fila.getString(2);

            /////  para consulta nombre alumno de mysql  ////
            hiloconexion = new ObtenerWebService4();
            String cadenaauxiliar = consultar_nombrealumno_id + "?codigo_alu="+codigo_alu.toString()+"&basedatos="+basedatos.toString();
            hiloconexion.execute(cadenaauxiliar, "2");

            /////  para consulta curso alumno de mysql  ////
            hiloconexion5 = new ObtenerWebService5();
            String cadenaauxiliar5 = consultar_cursoalumno_id + "?codigo_alu="+codigo_alu.toString()+"&basedatos="+basedatos.toString();
            hiloconexion5.execute(cadenaauxiliar5, "2");


        } else{

            nombrealumno.setText("El alumno todavia no esta registrado.");
            // Toast.makeText(this,"El Alumno No esta ingresado",Toast.LENGTH_SHORT).show();
            bd.close();
        }






    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_inicio, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.button2:
                Intent intent1 = new Intent(this,MenuActivity.class);
                startActivity(intent1);
                break;
            default:
                break;

        }
    }

    public void iringreso(View v){

        Intent i = new Intent(this,NotasActivity.class);
        startActivity(i);
    }

    public void irmensajes(View v){

        Intent i = new Intent(this,MensajesActivity.class);
        startActivity(i);
    }


    /////   ****** obtener webservice  ******* //////////

    public class ObtenerWebService4 extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            nombrealumno.setText("");
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            nombrealumno.setText(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

                        String line;
                        while ((line = reader.readLine()) != null) {
                            result.append(line);        // Paso toda la entrada al StringBuilder
                        }

                        JSONObject respuestaJSON = new JSONObject(result.toString());   //Creo un JSONObject a partir del StringBuilder pasado a cadena

                        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("apellido_alu") + "  " +
                                        // alumnosJSON.getJSONObject(i).getString("nombre_tri") + " " +
                                       // alumnosJSON.getJSONObject(i).getString("nombre_prc") + " :  " +
                                        alumnosJSON.getJSONObject(i).getString("nombre_alu") + "\n";

                            }

                        } else if (resultJSON.equals("2")) {
                            devuelve = "No se encontro Informacion, verifique los datos registrados (codigo del alumno y colegio)";//result.toString();
                        }

                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return devuelve;
            }
            return null;
        }
    }
    ///////  FIN WEBSERVICE ///////////////////////7


    /////   ****** obtener webservice  ******* //////////

    public class ObtenerWebService5 extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            cursoalumno.setText("");
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            cursoalumno.setText(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

                        String line;
                        while ((line = reader.readLine()) != null) {
                            result.append(line);        // Paso toda la entrada al StringBuilder
                        }

                        JSONObject respuestaJSON = new JSONObject(result.toString());   //Creo un JSONObject a partir del StringBuilder pasado a cadena

                        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_niv") + "  ' " +
                                        // alumnosJSON.getJSONObject(i).getString("nombre_tri") + " " +
                                        // alumnosJSON.getJSONObject(i).getString("nombre_prc") + " :  " +
                                        alumnosJSON.getJSONObject(i).getString("nombre_par") + " '\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;
        }
    }
    ///////  FIN WEBSERVICE ///////////////////////7




}
