package cpm.com.gskmtorange.gsk_dailyentry;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GetterSetter.AddittionalGetterSetter;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.xmlGetterSetter.AdditionalQuestiongetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.AuditDataGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.CategoryGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.T2PGetterSetter;

public class CategoryListActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    TextView txt_categoryName;

    ArrayList<CategoryGetterSetter> categoryList;
    CategoryListAdapter adapter;

    GSKOrangeDB db;
    String store_id, visit_date, username, intime, date, keyAccount_id, class_id, storeType_id,camera_allow, country_id;
    private SharedPreferences preferences;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        db = new GSKOrangeDB(this);
        db.open();

        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        CommonFunctions.updateLangResources(getApplicationContext(), preferences.getString(CommonString.KEY_LANGUAGE, ""));

        store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        date = preferences.getString(CommonString.KEY_DATE, null);
        username = preferences.getString(CommonString.KEY_USERNAME, null);
        intime = preferences.getString(CommonString.KEY_STORE_IN_TIME, "");
        keyAccount_id = preferences.getString(CommonString.KEY_KEYACCOUNT_ID, "");
        class_id = preferences.getString(CommonString.KEY_CLASS_ID, "");
        storeType_id = preferences.getString(CommonString.KEY_STORETYPE_ID, "");
        camera_allow = preferences.getString(CommonString.KEY_CAMERA_ALLOW, "");
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, null);


        /*txt_categoryName = (TextView) findViewById(R.id.txt_categoryName);
        txt_categoryName.setText(getResources().getString(R.string.title_activity_category_list));*/
        toolbar.setTitle(getResources().getString(R.string.title_activity_category_list));
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_category);
        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();
            }
        });
    }

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

        CommonFunctions.updateLangResources(getApplicationContext(), preferences.getString(CommonString.KEY_LANGUAGE, ""));

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        categoryList = new ArrayList<>();

        if(country_id.equals("7")){
            categoryList = db.getCategoryListData(null, null, null, store_id);
        }
        else {
            categoryList = db.getCategoryListData(keyAccount_id, storeType_id, class_id, store_id);
        }

        if (categoryList.size() > 0) {

            for (int i = 0; i < categoryList.size(); i++) {

                boolean flag_filled = false;
                String category_id = categoryList.get(i).getCategory_id();

                //Additional_Visibility
                if (db.additionalVisibilitydata(store_id, category_id)) {
                    boolean flag = true;

                    //MSL_Availability
                    /*if (db.isMappingStockDataMSL_Availability(category_id, keyAccount_id, storeType_id, class_id)) {
                        if (!db.checkMsl_AvailabilityData(store_id, category_id)) {
                            flag = false;
                        }
                    }

                    //Stock_Facing
                    if (flag) {
                        if (db.isMappingStockDataStockFacing(category_id, keyAccount_id, storeType_id, class_id)) {
                            if (!db.checkStockAndFacingData(store_id, category_id)) {
                                flag = false;
                            }
                        }
                    }*/

                    boolean flag_mapping_stock;
                    //New MSL_Availability_StockFacing
                    if(country_id.equals("7")){
                        flag_mapping_stock = db.isMappingStockDataStockFacing(category_id, null, null, null, store_id);
                    }
                    else {
                        flag_mapping_stock = db.isMappingStockDataStockFacing(category_id, keyAccount_id, storeType_id, class_id, store_id);
                    }
                    if (flag_mapping_stock) {
                        if (!db.checkMsl_Availability_StockFacingData(store_id, category_id)) {
                            flag = false;
                        }
                    }

                    //Promo Compliance
                    if (flag) {
                        if (db.isMappingPromotionData(store_id, category_id)) {
                            if (!db.checkPromoComplianceData(store_id, category_id)) {
                                flag = false;
                            }
                        }
                    }

                    //T2P
                    if (flag) {
                        if (db.isMappingT2PData(store_id, category_id)) {
                            if (!db.isFilledT2P(store_id, category_id)) {
                                flag = false;
                            }
                        }
                    }

                    //Category image
                    if (camera_allow.equalsIgnoreCase("1")) {
                        //if (category_camera_list.size()>0) {
                        if (!db.isCategoryPictureData(store_id, category_id)) {
                            flag = false;

                        }
                    }

                    if (flag){

                        //changed on 23.10.2018
                        //ArrayList<AuditDataGetterSetter> question_list = getAuditAfterDeletion(category_id);
                        //changed on 03.12.2018
                        ArrayList<AuditDataGetterSetter> question_list = getAuditQnsRemoved(category_id);

                        if(question_list.size()>0){

                            if(db.getAfterSaveAuditQuestionAnswerData(store_id, category_id).size() == 0){
                                flag = false;

                            }
                        }
                    }

                    flag_filled = flag;
                }

                if (flag_filled) {
                    if (category_id.equals("1")) {
                        categoryList.get(i).setCategory_img(R.mipmap.nutritionals_tick);
                    } else if (category_id.equals("2")) {
                        categoryList.get(i).setCategory_img(R.mipmap.oralcare_tick);
                    } else if (category_id.equals("3")) {
                        categoryList.get(i).setCategory_img(R.mipmap.wellness_tick);
                    }
                } else {
                    if (category_id.equals("1")) {
                        categoryList.get(i).setCategory_img(R.mipmap.nutritionals);
                    } else if (category_id.equals("2")) {
                        categoryList.get(i).setCategory_img(R.mipmap.oral_care);
                    } else if (category_id.equals("3")) {
                        categoryList.get(i).setCategory_img(R.mipmap.wellness);
                    }
                }
            }

            adapter = new CategoryListAdapter(CategoryListActivity.this, categoryList);
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));

            updateStatus();
        }

    }

    ArrayList<AuditDataGetterSetter> getAuditAfterDeletion(String category_id){
        ArrayList<AuditDataGetterSetter> question_list =  db.getAuditCategoryWise(category_id,storeType_id);

        Iterator<AuditDataGetterSetter> iterator = question_list.iterator();
        while (iterator.hasNext()) {
            AuditDataGetterSetter item = iterator.next(); // must be called before you can call iterator.remove()
            // Check condition
            if (!item.getKEYACCOUNT_ID().equals("0") && !item.getKEYACCOUNT_ID().equals(keyAccount_id)) {
                iterator.remove();
            } else if (!item.getCHECK_TYPE().equals("NA") && item.getCHECK_TYPE().equals("T2P")) {

                if (!db.isMappingT2PData(store_id, category_id)) {
                    iterator.remove();
                }
            }
        }

        return question_list;
    }

    ArrayList<AuditDataGetterSetter> getAuditQnsRemoved(String categoryId) {

        boolean t2p_flag = false;

        if (db.isMappingT2PData(store_id, categoryId)) {
            if (db.isFilledT2P(store_id, categoryId)) {
                ArrayList<T2PGetterSetter> t2PList = db.getT2pComplianceData(store_id, categoryId);

                for (int i = 0; i < t2PList.size(); i++) {
                    if (t2PList.get(i).getPresent() == 1) {
                        t2p_flag = true;
                        break;
                    }
                }
            }
        }

        if (!t2p_flag) {
            if (db.additionalVisibilitydata(store_id, categoryId)) {
                ArrayList<AddittionalGetterSetter> additionalList = db.getAdditionalMainStock(store_id, categoryId);

                for (int i = 0; i < additionalList.size(); i++) {
                    if (additionalList.get(i).getBtn_toogle().equals("1")) {
                        t2p_flag = true;
                        break;
                    }
                }
            }
        }

        ArrayList<AuditDataGetterSetter> question_list = db.getAuditCategoryWise(categoryId, storeType_id);

        Iterator<AuditDataGetterSetter> iterator = question_list.iterator();
        while (iterator.hasNext()) {
            AuditDataGetterSetter item = iterator.next(); // must be called before you can call iterator.remove()
            // Check condition
            if (!item.getKEYACCOUNT_ID().equals("0") && !item.getKEYACCOUNT_ID().equals(keyAccount_id)) {
                iterator.remove();
            } else if (!item.getCHECK_TYPE().equals("NA") && item.getCHECK_TYPE().equals("T2P")) {

                if (!t2p_flag) {
                    iterator.remove();
                }

            }
        }

        return question_list;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.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();

        if (id == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
    }

    public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.MyViewHolder> {
        List<CategoryGetterSetter> list = Collections.emptyList();
        Context context;
        private LayoutInflater inflator;

        public CategoryListAdapter(CategoryListActivity context, List<CategoryGetterSetter> list) {
            inflator = LayoutInflater.from(context);
            this.list = list;
            this.context = context;
        }

        @Override
        public CategoryListAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.category_menu_row, parent, false);
            MyViewHolder holder = new MyViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            final CategoryGetterSetter categoryData = list.get(position);

            holder.categoryName.setText(categoryData.getCategory());

            holder.categoryIcon.setImageResource(categoryData.getCategory_img());

            holder.lay_menu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(CategoryListActivity.this, CategoryWisePerformanceActivity.class);
                    intent.putExtra("categoryName", categoryData.getCategory());
                    intent.putExtra("categoryId", categoryData.getCategory_id());
                    startActivity(intent);
                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView categoryName;
            ImageView categoryIcon;
            LinearLayout lay_menu;

            public MyViewHolder(View itemView) {
                super(itemView);
                categoryName = (TextView) itemView.findViewById(R.id.categoryName);
                categoryIcon = (ImageView) itemView.findViewById(R.id.categoryIcon);
                lay_menu = (LinearLayout) itemView.findViewById(R.id.lay_menu);
            }
        }
    }

    public void updateStatus() {
        //Update Checkout Status
        boolean flag_filled = false;

        for (int i = 0; i < categoryList.size(); i++) {
            String category_id = categoryList.get(i).getCategory_id();

          /*  if (db.checkMsl_AvailabilityData(store_id, category_id)
                    && db.checkStockAndFacingData(store_id, category_id)
                    && db.checkPromoComplianceData(store_id, category_id)
                    && db.isFilledT2P(store_id, category_id)
                    && db.additionalVisibilitydata(store_id, category_id)) {

                flag_filled = true;
            } else {
                flag_filled = false;
                break;
            }*/

            if (db.additionalVisibilitydata(store_id, category_id)) {
                //boolean flag = true;

                /*if (db.isMappingStockDataMSL_Availability(category_id, keyAccount_id, storeType_id, class_id)) {
                    if (!db.checkMsl_AvailabilityData(store_id, category_id)) {
                        flag_filled = false;
                        break;
                    }
                }

                //Stock_Facing
                if (db.isMappingStockDataStockFacing(category_id, keyAccount_id, storeType_id, class_id)) {
                    if (!db.checkStockAndFacingData(store_id, category_id)) {
                        flag_filled = false;
                        break;
                    }
                }*/

                boolean flag_mapping_stock;
                //New MSL_Availability_StockFacing
                if(country_id.equals("7")){
                    flag_mapping_stock = db.isMappingStockDataStockFacing(category_id, null, null, null, store_id);
                }
                else {
                    flag_mapping_stock = db.isMappingStockDataStockFacing(category_id, keyAccount_id, storeType_id, class_id, store_id);
                }
                if (flag_mapping_stock) {
                    if (!db.checkMsl_Availability_StockFacingData(store_id, category_id)) {
                        flag_filled = false;
                        break;
                    }
                }

                if (db.isMappingPromotionData(store_id, category_id)) {
                    if (!db.checkPromoComplianceData(store_id, category_id)) {
                        flag_filled = false;
                        break;
                    }
                }


                if (db.isMappingT2PData(store_id, category_id)) {
                    if (!db.isFilledT2P(store_id, category_id)) {
                        flag_filled = false;
                        break;
                    }

                }

                if (camera_allow.equalsIgnoreCase("1")) {
                    //if (category_camera_list.size()>0) {
                    if (!db.isCategoryPictureData(store_id, category_id)) {
                        flag_filled = false;
                        break;
                    }
                }

                if(getAuditQnsRemoved(category_id).size()>0){

                    if(db.getAfterSaveAuditQuestionAnswerData(store_id, category_id).size() == 0){
                        flag_filled = false;
                        break;
                    }
                }

                flag_filled = true;
            } else {
                flag_filled = false;
                break;
            }
        }

        if (flag_filled) {
            db.updateCheckoutStatus(store_id, CommonString.KEY_VALID, CommonString.KEY_JOURNEY_PLAN);
        }
    }


}
