package com.example.martin.projetv5;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
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 java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements PriseAdapterMenu.PriseAdapterListener {

    ArrayList<Prise2> listPrises = new ArrayList<>();
    PriseAdapterMenu adapter = null;
    ListView list = null;

    String res = "";

    StringBDD eventBDD = null;

    String filepath=null;
    boolean fini;

    public void gestionHeure(){
        supList(listPrises);

        long now = System.currentTimeMillis();
        int cpt = 0;

        for(int w=0; w<eventBDD.getIndiceMaxPrise(); w++){
            Prise2 p = eventBDD.getPriseWithId(w+1);

            if (p != null) {
                String[] decoupeDate = p.getHeure().split("h");
                Calendar h_prise = Calendar.getInstance();
                h_prise.set(Calendar.HOUR_OF_DAY, Integer.parseInt(decoupeDate[0]));
                h_prise.set(Calendar.MINUTE, Integer.parseInt(decoupeDate[1]));
                long valeurDate = h_prise.getTimeInMillis();

                Calendar h2 = Calendar.getInstance();
                h2.set(Calendar.HOUR_OF_DAY, 2);
                h2.set(Calendar.MINUTE, 0);
                long valeur2h = h2.getTimeInMillis();

                if(now < valeur2h && valeurDate >= valeur2h+3600000*20){
                    valeurDate -= 3600000*24;
                }
                if((now >= valeurDate && now <= valeurDate+3600000*2 && p.getEffectuee().equals("false"))) {
                    addElementList(p, listPrises);
                    cpt++;
                }

                if(now > valeurDate+3600000*2) {
                    if(p.getEffectuee().equals("false")){
                        supElementList(p,listPrises);
                        Intent i = new Intent(this,ServiceInitAlarme.class);
                        i.putExtra("heure",p.getHeure());
                        startService(i);
                    }
                    else{
                        p.setEffectuee("true");
                        eventBDD.updatePrise(p.getId(),p);
                    }
                }
            }
        }
        if(cpt == 0){
            TextView textView = (TextView) findViewById(R.id.présence);
            textView.setText(R.string.menu2);
        }
        else{
            TextView textView = (TextView) findViewById(R.id.présence);
            textView.setText("");
        }
    }

    public void onClickVomi(View view){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.menu3);

        DialogInterface.OnClickListener onClickYes = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Date date = new Date();
                SimpleDateFormat f1 = new SimpleDateFormat("dd/MM/yyyy");
                SimpleDateFormat f2 = new SimpleDateFormat("HH:mm");

                String sEv = getString(R.string.menu9) + " " + f2.format(date);
                Event ev = new Event(eventBDD.getIndiceMaxEvent()+1,f1.format(date),f2.format(date),sEv);
                eventBDD.insertEvent(ev);

                long now = System.currentTimeMillis();

                for(int i=0; i<eventBDD.getIndiceMaxPrise(); i++){
                    Prise2 p = eventBDD.getPriseWithId(i+1);

                    String[] decoupeDate = p.getHeure().split("h");
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(decoupeDate[0]));
                    calendar.set(Calendar.MINUTE,Integer.parseInt(decoupeDate[1]));
                    long valeurDate = calendar.getTimeInMillis();

                    if(now <= valeurDate+3600000*2){
                        p.setEffectuee("false");
                        eventBDD.updatePrise(p.getId(),p);
                    }
                }
                onResume();
            }
        };

        builder.setMessage(getString(R.string.menu8));
        builder.setPositiveButton(R.string.oui,onClickYes);
        builder.setNegativeButton(R.string.non,null);
        builder.show();
    }

    public void onClickButton(final Prise2 item, int position){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.menu3);

        final Medicament medocAssocie = eventBDD.getMedocWithId(item.getIdMedoc());

        DialogInterface.OnClickListener onClickYes = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                supElementList(item, listPrises);
                displayConfirmation(list);

                Prise2 p = eventBDD.getPriseWithId(item.getId());
                p.setEffectuee("true");
                eventBDD.updatePrise(p.getId(),p);

                Intent i = new Intent(MainActivity.this,ServiceInitAlarme.class);
                i.putExtra("heure",p.getHeure());
                startService(i);

                Date date = new Date();
                SimpleDateFormat f1 = new SimpleDateFormat("dd/MM/yyyy");
                SimpleDateFormat f2 = new SimpleDateFormat("HH:mm");

                String sEv = medocAssocie.getNom1() + " " + getString(R.string.menu7) + " " + f2.format(date);
                Event ev = new Event(eventBDD.getIndiceMaxEvent()+1,f1.format(date),f2.format(date),sEv);
                eventBDD.insertEvent(ev);
            }
        };

        builder.setMessage(getString(R.string.menu4) + medocAssocie.getNom1() + " ?");
        builder.setPositiveButton(R.string.oui,onClickYes);
        builder.setNegativeButton(R.string.non,null);
        builder.show();
    }

    void supElementList(Prise2 p, ArrayList<Prise2> listP){
        listP.remove(p);
        adapter.notifyDataSetChanged();
    }

    void supList(ArrayList<Prise2> listP){
        listP.clear();
        adapter.notifyDataSetChanged();
    }

    void addElementList(Prise2 p, ArrayList<Prise2> listP){
        listP.add(p);
        adapter.notifyDataSetChanged();
    }

    public void displayConfirmation(View view) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, R.string.menu6, duration);
        toast.setGravity(Gravity.CENTER ,0,0);
        toast.show();
    }

    public void onClickHistorique(View view){
        Intent i = new Intent(this, HistoriqueActivity.class);
        startActivity(i);
    }

    public void onClickGestionMedoc(View view){
        Intent i = new Intent(this, GestionActivity.class);
        startActivity(i);
    }

    public String chargementMedoc(String codeSource){
        String nomMedoc = null, nomMolecule = null;
        String posologie = null, indications = null;
        String nomImage = null;
        int i2 = codeSource.indexOf("</h2>");
        codeSource = codeSource.substring(i2+4);
        int i1 = codeSource.indexOf("<h2>")+4;
        i2 = codeSource.indexOf("(");
        if(i1 != -1 && i2 != -1){
            nomMedoc = codeSource.substring(i1, i2);
            i1 = codeSource.indexOf("(")+1;
            i2 = codeSource.indexOf(")");
            nomMolecule = codeSource.substring(i1, i2);
        }

        i1 = codeSource.indexOf("<p><img");
        i2 = codeSource.indexOf("</p>");
        String image = codeSource.substring(i1,i2);
        i1 = image.indexOf("src=./")+6;
        i2 = image.indexOf("alt=")-1;
        if(i1 != -1 && i2 != -1) nomImage = image.substring(i1,i2);

        i1 = codeSource.indexOf("<h2>Posologie</h2>") + 18;
        i2 = codeSource.indexOf("<a name=content></a><h2>Indications</h2>");
        if(i1 != -1 && i2 != -1) posologie = codeSource.substring(i1, i2);
        i1 = codeSource.indexOf("<h2>Indications</h2>") + 20;
        i2 = codeSource.indexOf("</form>");
        if(i1 != -1 && i2 != -1) indications = codeSource.substring(i1, i2);
        String s = nomMedoc + "XoXo" + nomMolecule + "XoXo" + nomImage + "XoXo" + posologie + "XoXo" + indications;
        return s;
    }

    public void onClickDownload(View view){
        final ImageButton imageButton = (ImageButton) findViewById(R.id.download);
        imageButton.setColorFilter(R.color.colorPrimaryDark);

        fini = false;

        new AsyncTask<String, Void, String>(){
            @Override
            protected String doInBackground(String... urlStr){
                String htmlCode = "";
                try{
                    URL url = new URL(urlStr[0]);
                    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        htmlCode += inputLine;
                    }
                    in.close();

                } catch (Exception e) {e.printStackTrace(); fini = true;}
                return htmlCode.toString();
            }

            @Override
            protected void onPostExecute(String codeSource){

                ArrayList<String> noms = new ArrayList<String>();
                int i1 = codeSource.indexOf("<ul><li><a")+19;
                int i2 = codeSource.indexOf(".html")+5;
                while(i1 != -1 && i2 != -1 && i1<i2){
                    String nom = codeSource.substring(i1, i2);
                    noms.add(nom);
                    codeSource = codeSource.substring(i2+2+(i2-i1));
                    i1 = codeSource.indexOf("./");
                    i2 = codeSource.indexOf(".html")+5;
                }

                for(String s : noms){
                    new AsyncTask<String, Void, String>(){
                        @Override
                        protected String doInBackground(String... urlStr){
                            String htmlCode = "";
                            try{
                                URL url = new URL(urlStr[0]);
                                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

                                String inputLine;
                                while ((inputLine = in.readLine()) != null) {
                                    htmlCode += inputLine;
                                }
                                in.close();
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                                fini = true;
                            } catch (IOException e) {
                                filepath=null;
                                e.printStackTrace();
                                fini = true;
                            }
                            return htmlCode.toString();
                        }

                        @Override
                        protected void onPostExecute(String codeSourcePage){
                            res += chargementMedoc(codeSourcePage);

                            String[] medocdoc = res.split("XoXo");
                            String nom = medocdoc[0];
                            String nomImage = medocdoc[2];

                            new AsyncTask<String, Void, String>(){
                                @Override
                                protected String doInBackground(String... urlStr){
                                    String htmlCode = "";
                                    try{
                                        File SDCardRoot = Environment.getExternalStorageDirectory();
                                        String dossier = "medicaments";
                                        File file2 = new File(SDCardRoot,dossier);
                                        file2.mkdir();
                                        if(file2.createNewFile())
                                        {
                                            file2.createNewFile();
                                        }

                                        URL url = new URL(urlStr[0]);
                                        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                                        urlConnection.setRequestMethod("GET");
                                        urlConnection.setDoOutput(true);
                                        urlConnection.connect();

                                        String filename = urlStr[0].substring(25);
                                        int i = filename.indexOf(".");
                                        filename = filename.substring(0,i)+".png";

                                        File file = new File(SDCardRoot+"/"+dossier,filename);
                                        file.isFile();
                                        if(file.createNewFile())
                                        {
                                            file.createNewFile();
                                        }
                                        FileOutputStream fileOutput = new FileOutputStream(file);
                                        InputStream inputStream = urlConnection.getInputStream();
                                        int totalSize = urlConnection.getContentLength();
                                        int downloadedSize = 0;
                                        byte[] buffer = new byte[1024];
                                        int bufferLength;
                                        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                                            fileOutput.write(buffer, 0, bufferLength);
                                            downloadedSize += bufferLength;
                                        }
                                        fileOutput.close();
                                        if(downloadedSize==totalSize)   filepath=file.getPath();

                                    } catch (MalformedURLException e) {
                                        e.printStackTrace();
                                        fini = true;
                                    } catch (IOException e) {
                                        filepath=null;
                                        e.printStackTrace();
                                        fini = true;
                                    }
                                    return htmlCode.toString();
                                }

                                @Override
                                protected void onPostExecute(String codeSourcePage){
                                }

                                @Override
                                protected void onCancelled(){
                                    super.onCancelled();
                                    Toast.makeText(MainActivity.this,R.string.menu5,Toast.LENGTH_SHORT).show();
                                    fini = true;
                                }
                            }.execute("http://pharmacie.plil.fr/"+nomImage);

                            boolean existe = false;
                            int indice = 0;
                            int w=1;
                            while(w <= eventBDD.getIndiceMaxMedoc() && !existe) {
                                Medicament m = eventBDD.getMedocWithId(w);
                                if (m.getNom1().equals(nom)){
                                    existe = true;
                                    indice = m.getIdM();
                                }
                                w++;
                            }
                            if(!existe) {
                                int i  = medocdoc[2].indexOf(".");
                                medocdoc[2] = medocdoc[2].substring(0,i)+".png";
                                medocdoc[2] = Environment.getExternalStorageDirectory().toString()+"/medicaments/"+medocdoc[2];
                                Medicament m = new Medicament(eventBDD.getIndiceMaxMedoc()+1,medocdoc[0],medocdoc[1],medocdoc[3],medocdoc[4],medocdoc[2]);
                                eventBDD.insertMedoc(m);
                            }
                            else{
                                int i  = medocdoc[2].indexOf(".");
                                medocdoc[2] = medocdoc[2].substring(0,i)+".png";
                                medocdoc[2] = Environment.getExternalStorageDirectory().toString()+"/medicaments/"+medocdoc[2];
                                Medicament m = new Medicament(indice,medocdoc[0],medocdoc[1],medocdoc[3],medocdoc[4],medocdoc[2]);
                                eventBDD.updateMedoc(indice,m);
                            }
                            res = "";
                        }
                    }.execute("http://pharmacie.plil.fr/"+s);
                }
                imageButton.clearColorFilter();
                if(fini) Toast.makeText(MainActivity.this,R.string.menu5,Toast.LENGTH_SHORT).show();
                else Toast.makeText(MainActivity.this,R.string.menu10,Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onCancelled(){
                super.onCancelled();
                imageButton.clearColorFilter();
                Toast.makeText(MainActivity.this,R.string.menu5,Toast.LENGTH_SHORT).show();
            }

        }.execute("http://pharmacie.plil.fr/liste_fiche.php");
    }

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

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);

        eventBDD = new StringBDD(this);
        eventBDD.open();
    }

    @Override
    protected void onResume() {
        eventBDD.open();
        super.onResume();

        adapter = new PriseAdapterMenu(this,listPrises);
        adapter.addListener(this);
        list = (ListView)findViewById(R.id.list1);
        list.setAdapter(adapter);

        gestionHeure();
    }

    @Override
    protected void onPause() {
        eventBDD.close();
        super.onPause();

        adapter = new PriseAdapterMenu(this,listPrises);
        adapter.addListener(this);
        list = (ListView)findViewById(R.id.list1);
        list.setAdapter(adapter);

        supList(listPrises);
    }
}