package com.example.moslah_hamza.statsdemo;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class LimitActivity extends AppCompatActivity {

    RadioGroup periode;
    TextView catText;
    EditText montantEdit;
    List<String> modeList = new ArrayList<String>();
    String datedeb = "";
    String datefin = "";
    DatePickerDialog fromDatePickerDialog;
    DatePickerDialog toDatePickerDialog;
    DataBaseConnection db;
    Limite limite;
    String categ_id;
    Intent i;

    int PROFILE = R.drawable.ic_currency_usd_grey600_18dp;
    RecyclerView mRecyclerView;                           // Declaring RecyclerView
    RecyclerView.Adapter drAdapter;                        // Declaring Adapter For Recycler View
    RecyclerView.LayoutManager mLayoutManager;            // Declaring Layout Manager as a linear layout manager
    String TITLES[] = {"Suivre revenues","Suivre dépenses","Gérer catégories","Planifier","Events","Stats"};
    int ICONS[] = {R.drawable.ic_currency_usd_grey600_18dp,R.drawable.ic_currency_usd_grey600_18dp,R.drawable.ic_wrench_grey600_18dp,
            R.drawable.ic_currency_usd_grey600_18dp, R.drawable.ic_calendar_grey600_18dp,R.drawable.ic_poll_box_grey600_18dp};
    DrawerLayout Drawer;                                  // Declaring DrawerLayout
    ActionBarDrawerToggle mDrawerToggle;                  // Declaring Action Bar Drawer Toggle
    String NAME = "Money Tracker";
    String EMAIL = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_limit);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mRecyclerView=new RecyclerView(this);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler1); // Assigning the RecyclerView Object to the xml View

        mRecyclerView.setHasFixedSize(true);                            // Letting the system know that the list objects are of fixed size
        drAdapter= new MyAdapter(TITLES, ICONS, NAME, EMAIL, PROFILE, new OnItemClickListener() {
            @Override
            public void onItemClick(View item,int position) {
                displayView(position);
                Drawer.closeDrawers();
            }
        });       // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
        // And passing the titles,icons,header view name, header view email,
        // and header view profile picture
        mRecyclerView.setAdapter(drAdapter);                              // Setting the adapter to RecyclerView
        mLayoutManager = new LinearLayoutManager(this);                 // Creating a layout Manager
        mRecyclerView.setLayoutManager(mLayoutManager);                 // Setting the layout Manager

        Drawer = (DrawerLayout) findViewById(R.id.drawer_layout);        // Drawer object Assigned to the view
        mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
                // open I am not going to put anything here)
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                // Code here will execute once drawer is closed
            }
        }; // Drawer Toggle Object Made
        Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
        mDrawerToggle.syncState();               // Finally we set the drawer toggle sync State

        i=getIntent();
        categ_id=i.getStringExtra("CAT");
       // Log.d("category description",categ_id);
        db = new DataBaseConnection(this);
        db.createDataBase();
        catText= (TextView) findViewById(R.id.categorie);
        catText.setText(categ_id);

        getLimite();
        if(limite.getMontant()==0){
            LinearLayout layout= (LinearLayout) findViewById(R.id.limit_lay);
            layout.setVisibility(LinearLayout.GONE);
        }

        ImageView catIcon=(ImageView)findViewById(R.id.catIcon);
        TextView catName=(TextView)findViewById(R.id.cat_name);
        TextView montant=(TextView)findViewById(R.id.montant);
        TextView periode=(TextView)findViewById(R.id.limit_period);
        final ImageButton limit_del= (ImageButton) findViewById(R.id.limit_del);
        limit_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(LimitActivity.this, limit_del);
                final MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.limit_pop, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        if(item.getItemId()==R.id.remove_limit){
                            db.deleteLimite(limite);
                            Intent i=new Intent(LimitActivity.this,LimitActivity.class);
                            i.putExtra("CAT",categ_id);
                            startActivity(i);
                        }
                        return false;
                    }
                });
                popup.show();
            }
        });

        catName.setText(limite.getCat());
        montant.setText(String.valueOf(limite.getMontant()));
        periode.setText(limite.getMode()+" "+limite.getDateDebut()+" "+limite.getDateFin());

        Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);

        fromDatePickerDialog = new DatePickerDialog(LimitActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    TextView txtDate1 = (TextView) findViewById(R.id.DateDEbText);

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        txtDate1.setText(dayOfMonth + "-"
                                + (monthOfYear + 1) + "-" + year);
                        Log.d("hamza", txtDate1.getText().toString());
                        datedeb = (dayOfMonth + "-"
                                + (monthOfYear + 1) + "-" + year);
                    }
                }, mYear, mMonth, mDay);

        c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        toDatePickerDialog = new DatePickerDialog(LimitActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    TextView txtDate2 = (TextView) findViewById(R.id.DateFinText);

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        txtDate2.setText(dayOfMonth + "-"
                                + (monthOfYear + 1) + "-" + year);
                        datefin = (dayOfMonth + "-"
                                + (monthOfYear + 1) + "-" + year);
                    }
                }, mYear, mMonth, mDay);

        modeList = DefinirPeriode();
        Button valider = (Button) findViewById(R.id.valider);
        valider.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CreerLimite();
                Intent intent = new Intent(LimitActivity.this, LimitActivity.class);
                intent.putExtra("CAT",categ_id);
                startActivity(intent);
            }
        });

    }

    public List<String> DefinirPeriode ()
    {
        final List<String> Retour = new ArrayList<String>();
        periode = (RadioGroup) findViewById(R.id.radioGroup);
        periode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup periode, int checkedId) {
                String p;
                TextView txtDate1 = (TextView) findViewById(R.id.DateDEbText);
                TextView txtDate2 = (TextView) findViewById(R.id.DateFinText);

                // This will get the radiobutton that has changed in its check state
                RadioButton radioButton = (RadioButton) periode.findViewById(checkedId);
                if ((radioButton.getText()).equals("Par jour.")) {
                    p = "par jour";
                    Retour.add(p);
                    Button DateDeb = (Button) findViewById(R.id.dateDebicon);
                    DateDeb.setClickable(false);
                    Button DateFin = (Button) findViewById(R.id.dateFinicon);
                    DateFin.setClickable(false);
                    txtDate1.setText("");
                    txtDate2.setText("");

                } else {
                    if ((radioButton.getText()).equals("Par semaine.")) {
                        p = "par semaine";
                        Retour.clear();
                        Retour.add(p);
                        Button DateDeb = (Button) findViewById(R.id.dateDebicon);
                        DateDeb.setClickable(false);
                        Button DateFin = (Button) findViewById(R.id.dateFinicon);
                        DateFin.setClickable(false);
                        txtDate1.setText("");
                        txtDate2.setText("");

                    } else {
                        if ((radioButton.getText()).equals("Par mois.")) {
                            p = "par mois";
                            Retour.clear();
                            Retour.add(p);
                            Button DateDeb = (Button) findViewById(R.id.dateDebicon);
                            DateDeb.setClickable(false);
                            Button DateFin = (Button) findViewById(R.id.dateFinicon);
                            DateFin.setClickable(false);
                            txtDate1.setText("");
                            txtDate2.setText("");

                        } else {
                            p = "pesonaliser";
                            Retour.clear();
                            Retour.add(p);
                            Button DateDeb = (Button) findViewById(R.id.dateDebicon);
                            DateDeb.setClickable(true);
                            Button DateFin = (Button) findViewById(R.id.dateFinicon);
                            DateFin.setClickable(true);
                            DateDeb.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    fromDatePickerDialog.show();
                                }
                            });

                            DateFin.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    Log.d("3asssllllemaFIn", "tag");
                                    toDatePickerDialog.show();
                                }
                            });

                        }
                    }
                }
            }
        });
        return Retour;
    }

    public void CreerLimite() {
        Limite l = null;
        catText = (TextView) findViewById(R.id.categorie);
        String cat = catText.getText().toString();
        montantEdit = (EditText) findViewById(R.id.limite);
        float montant = Float.parseFloat((montantEdit.getText()).toString());
        String mode = modeList.get(0);
        if (mode.equals("pesonaliser")) {

            l = new Limite(montant, datedeb, datefin, cat, mode);
            Log.d(l.toString(), "logtoString");
            Log.d(mode, "mode");
        }

        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addLimite(new Limite(montant, datedeb, datefin, cat, mode));

        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        List<Limite> Limites = db.getAllLimits();

        for (Limite lmt : Limites) {
            String log = "Id: " + lmt.getLimitId() + " ,Catégorie: " + lmt.getCat() + " ,Montant: " +
                    lmt.getMontant() + ",DateDeb " +lmt.getDateDebut()+ ",DateFin " + lmt.getDateFin() + ",Mode" +lmt.getMode();
            // Writing Contacts to log
            Log.d("Limite::::", log);
        }
    }

    public void getLimite()
    {
        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        limite= db.getLimite(categ_id);
    }

    private void displayView(int position) {
        if(position==3){
            Intent intent=new Intent(LimitActivity.this,CategoryAct.class);
            startActivity(intent);
        }
        if(position==1){
            Intent intent=new Intent(LimitActivity.this,MainActivity.class);
            startActivity(intent);
        }
    }
}