package com.example.moslah_hamza.statsdemo;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {

    ArrayList<Float> sommes1 = new ArrayList<Float>();
    ArrayList<Float> sommes2 = new ArrayList<Float>();
    float sumtot;
    ArrayList<String> categories1 = new ArrayList<String>();
    ArrayList<String> categories2 = new ArrayList<String>();
    RecyclerView mRecycler;
    RecyclerView.Adapter mAdapter;
    private DataBaseTranHandler db;
    ArrayList<Categorie> categList =new ArrayList<Categorie>();
    ArrayList<Transaction> transactions= new ArrayList<Transaction>();
    ExpandableListView expListView;
    ExpandableListAdapter expandableListAdapter;
    ExpandableListView expListView1;
    ExpandableListAdapter expandableListAdapter1;
    TextView balance;
    Intent i;

    int PROFILE = R.drawable.ic_currency_usd_grey600_18dp;
    RecyclerView mRecyclerView;                           // Declaring RecyclerView
    RecyclerView.Adapter myAdapter;                        // 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 = "";

    DataBaseHandler dbcat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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
        myAdapter= 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(myAdapter);                              // 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

        // Load Fragment1 when the app starts
        //displayView(1);

        TextView cat= (TextView) findViewById(R.id.cat);
        TextView percent= (TextView) findViewById(R.id.percent);
       // LinearLayout linearLayout= (LinearLayout) findViewById(R.id.linearstats);

        db=new DataBaseTranHandler(this);
        db.createdb();
        /*db.addDipense(new Transaction(30, 1, "15/03/2016"));
        db.addDipense(new Transaction(10, 2, "15/03/2016"));

        db.addRevenue(new Transaction(30, 3, "15/03/2016"));
        db.addRevenue(new Transaction(10, 4, "15/03/2016"));*/

        dbcat=new DataBaseHandler(this);
        dbcat.createdb();
        //dbcat.addContact(new Categorie("Shopping", 1, "Dépense"));
      //  Log.d("category", dbcat.getContact("Shopping").getType());
        categList= (ArrayList<Categorie>) dbcat.getAllCategories("Dépense");

        getDipenses();
        pourcentage("Dépenses");

        // get the listview
        expListView = (ExpandableListView) findViewById(R.id.lvExp);
        // get the listview
        expListView1 = (ExpandableListView) findViewById(R.id.lvExp1);

        balance= (TextView) findViewById(R.id.balance);

        FloatingActionButton fab= (FloatingActionButton) findViewById(R.id.fab_add);

        i=new Intent(this,AddActivity.class);
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_add);
        dialog.setTitle("Ajouter une nouvelle transaction");
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(i);
                //dialog.show();
            }
        });

        Resources r = getResources();
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        final int px = Math.round(30 * (r.getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
        final int screenHeight = Math.round(30 * (r.getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
        final int screenWidth = Math.round(380 * (r.getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));

        final EditText ed= (EditText) dialog.findViewById(R.id.add_sum);
       // final Button bt= (Button) dialog.findViewById(R.id.add_bt);

       /* bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               /* db.addDipense(new Transaction(Float.valueOf(ed.getText().toString()), 2,
                        new SimpleDateFormat("EEE d MMM yyyy").format(Calendar.getInstance().getTime())));
                Log.d("edit text ",ed.getText().toString());
                if(!db.getDipense(2,
                        new SimpleDateFormat("EEE d MMM yyyy").format(Calendar.getInstance().getTime()))
                        .getDate().equals("")){
                    Log.d("Added Sum : ", "sum added successfully");
                    getDipenses();
                    pourcentage();
                    /*expListView.removeAllViews();
                    expandableListAdapter=new ExpandableListAdapter("Dépenses",sommes,categories,getApplicationContext(),
                            screenWidth,screenHeight,px);
                    expListView.setAdapter(expandableListAdapter);*/
                    //mRecycler.removeAllViews();
                    //mRecycler.setAdapter(new NewAdapter(sommes,categories,getApplication(),screenWidth,screenHeight,px));
               /* }else{
                    Log.d("Sum : ", "sum not added");
                }
                dialog.dismiss();*/
         /*   }
        });*/

        expandableListAdapter=new ExpandableListAdapter("Dépenses",sumtot,sommes1,categories1,this,screenWidth,screenHeight,px);
        expListView.setAdapter(expandableListAdapter);

        float sumDep=sumtot;

        categList.clear();
        categList= (ArrayList<Categorie>) dbcat.getAllCategories("Revenue");
        getRevenues();
        pourcentage("Revenues");

        balance.setText(String.valueOf(sumtot - sumDep)+" DT");
        if(sumtot-sumDep<0){
            balance.setTextColor(getResources().getColor(R.color.red));
        }else {
            balance.setTextColor(getResources().getColor(R.color.green));
        }

        expandableListAdapter1=new ExpandableListAdapter("Revenues",sumtot,sommes2,categories2,this,screenWidth,screenHeight,px);
        expListView1.setAdapter(expandableListAdapter1);
       /* mAdapter=new NewAdapter(sommes,categories,this,screenWidth,screenHeight,px);

        LinearLayoutManager mLayoutManager;
        mLayoutManager=new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycler= (RecyclerView) findViewById(R.id.recycler2);
        mRecycler.setLayoutManager(mLayoutManager);

        mRecycler.setAdapter(mAdapter);*/
    }

    //calculer le pourcentage des catégories
    public void pourcentage(String genre){
        float somme=0;
        ArrayList<Float> sommes;
        if(genre.equals("Dépenses")){
            sommes=sommes1;
        }else {
            sommes=sommes2;
        }

        for(int i=0; i<sommes.size();i++)
            somme+=sommes.get(i);

        float x=0;
        for(int i=0; i<sommes.size();i++){
            Log.d("Somme tot ", String.valueOf(somme));
            Log.d("Somme "+i, String.valueOf(sommes.get(i)));
            x=(sommes.get(i)/somme)*10000;
            Log.d("Somme before " + i, String.valueOf(x));
            Log.d("Somme after " + i, String.valueOf(Math.round(x)));
            sommes.set(i, Float.valueOf(Math.round(x))/100);
        }
        sumtot=somme;
    }

    //calculer la somme des transactions d'une catégorie
    public float calcul (ArrayList<Transaction> tr )
    {
        float somme=0;
        for (int i=0 ;i<tr.size();i++)
            somme=somme+tr.get(i).getSomme();
        return somme;
    }

    public void getDipenses() {
        sommes1.clear();
        categories1.clear();
        for(int j=0;j<categList.size();j++){
            transactions =db.getAllDipenses(categList.get(j).getDescription());
           // Log.d("transactions ",String.valueOf(transactions.get(j).getSomme()));
            sommes1.add(calcul(transactions));
            Log.d("Categorie ",categList.get(j).getDescription());
            categories1.add(categList.get(j).getDescription());
        }
    }

    public void getRevenues() {
        sommes2.clear();
        categories2.clear();
        Log.d("get ", "Revenues");
        for(int j=0;j<categList.size();j++){
            transactions = db.getAllRevenues(categList.get(j).getDescription());
            // Log.d("transactions ",String.valueOf(transactions.get(j).getSomme()));
            sommes2.add(calcul(transactions));
            Log.d("somme ", String.valueOf(j) + " " + String.valueOf(sommes2.get(j)));
            categories2.add(categList.get(j).getDescription());
        }
    }

    @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_main, 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);
    }

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