package com.example.martin.projetv5;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by martin on 28/02/2017.
 */

public class GestionActivity extends AppCompatActivity implements MedocAdapterMenu.MedocAdapterListener {

    ArrayList<Medicament> listMedocs = new ArrayList<>();
    MedocAdapterMenu adapter = null;
    ListView list = null;
    StringBDD eventBDD = null;

    void addElementList(Medicament m, ArrayList<Medicament> listM){
        listM.add(m);
        adapter.notifyDataSetChanged();
    }

    void supList(ArrayList<Medicament> listM){
        listM.clear();
        adapter.notifyDataSetChanged();
    }

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

    public void gestionList(){
        boolean present = false;
        for(int w=0; w<eventBDD.getIndiceMaxMedoc(); w++){
            boolean ok = false;
            Medicament m = eventBDD.getMedocWithId(w+1);
            int x=1;

            while(x <= eventBDD.getIndiceMaxPrise() && !ok){
                Prise2 p = eventBDD.getPriseWithId(x);
                if (p != null) {
                    if (p.getIdMedoc().equals(m.getIdM())) {
                        ok = true;
                        present = true;
                    }
                }
                x++;
            }

            if(ok) addElementList(m,listMedocs);
        }
        if(!present){
            TextView textView = (TextView) findViewById(R.id.aucunMedoc);
            textView.setText(R.string.gestion2);
        }
        else{
            TextView textView = (TextView) findViewById(R.id.aucunMedoc);
            textView.setText("");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gestion_layout);

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

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

        adapter = new MedocAdapterMenu(this,listMedocs);
        adapter.addListener(this);
        list = (ListView)findViewById(R.id.listMedoc);
        list.setAdapter(adapter);

        gestionList();
    }

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

        adapter = new MedocAdapterMenu(this,listMedocs);
        adapter.addListener(this);
        list = (ListView)findViewById(R.id.listMedoc);
        list.setAdapter(adapter);

        supList(listMedocs);
    }

    @Override
    public void onClickButton(Medicament item, int position) {
        Intent i = new Intent(this, ModifMedocActivity.class);
        i.putExtra("id",item.getIdM());
        startActivity(i);
    }
}
