package cpm.com.gskmtorange.dailyentry;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.xmlGetterSetter.BrandMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.ConfigurationMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MSL_AvailabilityStockFacingGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.PromoComplianceSkuwiseGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.SelectGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.SkuGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.SkuMasterGetterSetter;

public class AdditionalPromoSKUwiseActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {

    private Context context;
    GSKOrangeDB db;
    String store_id, visit_date, username, intime, date;
    String categoryName, categoryId;
    String sub_category = "", sub_category_id = "0", brand = "", brand_id = "0", sku = "", sku_id = "0", discount = "", price = "", _pathforcheck = "", _path = "", img_str = "", country_id;
    private SharedPreferences preferences;
    Spinner spinner_sub_category_list, spinner_brand_list, spinner_sku_list, sp_flasher;
    ArrayList<MSL_AvailabilityStockFacingGetterSetter> sub_category_list;
    ArrayList<BrandMasterGetterSetter> brand_list = new ArrayList<>();
    ArrayList<SkuMasterGetterSetter> sku_list = new ArrayList<>();
    Toolbar toolbar;
    FloatingActionButton fab_save, fab_add;

    ArrayList<PromoComplianceSkuwiseGetterSetter> exists_data = new ArrayList<>();
    ArrayList<PromoComplianceSkuwiseGetterSetter> added_promo_list = new ArrayList<>();

    RecyclerView rec_added_promo;
    EditText et_discount, et_price;
    String gallery_package = "";
    Uri outputFileUri;
    ImageView img_cam;
    boolean isdata_added = false, isExists = true, is_camera_compulsory = false;
    LinearLayout lin_parent;
    PromoAdapter promoAdapter;
    int price_flasher_available = -1;

    ToggleButton btntoggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_additional_promo_skuwise);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.title_activity_promo_compliance));
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        spinner_sub_category_list = (Spinner) findViewById(R.id.sp_sub_category);
        spinner_brand_list = (Spinner) findViewById(R.id.sp_brand);
        spinner_sku_list = (Spinner) findViewById(R.id.sp_sku);
        sp_flasher = (Spinner) findViewById(R.id.sp_flasher);
        fab_save = (FloatingActionButton) findViewById(R.id.fab);
        fab_add = (FloatingActionButton) findViewById(R.id.fab_add);
        rec_added_promo = (RecyclerView) findViewById(R.id.rec_added_promo_skuwise);
        et_discount = (EditText) findViewById(R.id.et_discount);
        et_price = (EditText) findViewById(R.id.et_price);
        img_cam = (ImageView) findViewById(R.id.img_promotion_add);
        lin_parent = (LinearLayout) findViewById(R.id.lin_parent_promo);
        btntoggle = (ToggleButton) findViewById(R.id.btntoggle);

        context = this;
        //preference data
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        store_id = preferences.getString(CommonString.KEY_STORE_ID, null);
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        username = preferences.getString(CommonString.KEY_USERNAME, null);
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, null);
        et_price.setKeyListener(DigitsKeyListener.getInstance(false, true));

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

        //Intent data
        categoryName = getIntent().getStringExtra("categoryName");
        categoryId = getIntent().getStringExtra("categoryId");

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

        //Enable camera compulsory According to Configuration
        ArrayList<ConfigurationMasterGetterSetter> configurationData = db.getConfigurationMasterData(country_id);
        if (configurationData.size() > 0) {
            for (int i = 0; i < configurationData.size(); i++) {

                if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("ADDITIONAL_PROMO_SKUWISE_IMAGE_MANDATORY") && configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                    is_camera_compulsory = true;
                }
            }
        }

        if (is_camera_compulsory) {
            img_cam.setBackgroundResource(R.drawable.camera_orange_star_green);
        }

        //Promo SKU List
        exists_data = db.getPromoComplianceSkuwiseExistsAfterData(store_id, categoryId);

        if (exists_data.size() > 0) {
            isExists = exists_data.get(0).isExists();
            if (exists_data.get(0).isExists()) {
                added_promo_list = db.getPromoComplianceSkuwiseAfterData(store_id, categoryId);
            } else {
                fab_add.hide();//.setVisibility(View.GONE);
                added_promo_list.clear();
                if (promoAdapter != null) {
                    promoAdapter.list.clear();
                    promoAdapter.notifyDataSetChanged();
                }

                lin_parent.setVisibility(View.GONE);
            }
        }

        btntoggle.setChecked(isExists);

        if (added_promo_list.size() > 0) {
            rec_added_promo.setLayoutManager(new LinearLayoutManager(context));
            promoAdapter = new PromoAdapter(added_promo_list);
            rec_added_promo.setAdapter(promoAdapter);
        }

        sub_category_list = db.getSubCategoryMasterSKUwise(categoryId);

        MSL_AvailabilityStockFacingGetterSetter sub_category = new MSL_AvailabilityStockFacingGetterSetter();
        String str = getResources().getString(R.string.select);
        sub_category.setSub_category(str);
        sub_category_list.add(0, sub_category);
        CustomSubCategoryAdapter adapter = new CustomSubCategoryAdapter(AdditionalPromoSKUwiseActivity.this, R.layout.custom_spinner_item, sub_category_list);

        spinner_sub_category_list.setAdapter(adapter);

        spinner_sub_category_list.setOnItemSelectedListener(this);

        ArrayList<SelectGetterSetter> ans_list = new ArrayList<>();
        SelectGetterSetter select = new SelectGetterSetter();
        select.setAns(getString(R.string.select));
        select.setAns_id(0);
        ans_list.clear();
        ans_list.add(select);

        select = new SelectGetterSetter();
        select.setAns(getString(R.string.yes));
        select.setAns_id(1);
        ans_list.add(select);

        select = new SelectGetterSetter();
        select.setAns(getString(R.string.no));
        select.setAns_id(2);
        ans_list.add(select);

        CustomSpinnerAdapter ansAdapter = new CustomSpinnerAdapter(AdditionalPromoSKUwiseActivity.this, R.layout.custom_t2p_spinner_item, ans_list);
        sp_flasher.setAdapter(ansAdapter);
        sp_flasher.setOnItemSelectedListener(this);

        fab_add.setOnClickListener(this);
        fab_save.setOnClickListener(this);
        img_cam.setOnClickListener(this);
        btntoggle.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        toolbar.setTitle(getResources().getString(R.string.title_activity_promo_compliance));
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        if (parent.getId() == R.id.sp_sub_category) {

            if (position != 0) {
                sub_category = sub_category_list.get(position).getSub_category();
                sub_category_id = sub_category_list.get(position).getSub_category_id();

                brand_list = db.getBrandMasterDataBySubCategory(sub_category_id);

                BrandMasterGetterSetter brand_select = new BrandMasterGetterSetter();
                String str = getResources().getString(R.string.select);
                brand_select.setBRAND(str);
                brand_select.setBRAND_ID("0");
                brand_list.add(0, brand_select);

                CustomBrandAdapter adapter = new CustomBrandAdapter(AdditionalPromoSKUwiseActivity.this, R.layout.custom_spinner_item, brand_list);
                spinner_brand_list.setAdapter(adapter);
                spinner_brand_list.setOnItemSelectedListener(this);
            } else {
                clearBrandSpinner();
            }

        } else if (parent.getId() == R.id.sp_brand) {

            if (position != 0) {
                brand = brand_list.get(position).getBRAND().get(0);
                brand_id = brand_list.get(position).getBRAND_ID().get(0);

                sku_list = db.getSKUMasterNewData(brand_id);

                SkuMasterGetterSetter sku_select = new SkuMasterGetterSetter();
                String str = getResources().getString(R.string.select);
                sku_select.setSKU(str);
                sku_select.setSKU_ID("0");
                sku_list.add(0, sku_select);

                CustomSkuAdapter adapter = new CustomSkuAdapter(AdditionalPromoSKUwiseActivity.this, R.layout.custom_spinner_item, sku_list);
                spinner_sku_list.setAdapter(adapter);
                spinner_sku_list.setOnItemSelectedListener(this);
            } else {
                clearSkuSpinner();
            }

        } else if (parent.getId() == R.id.sp_sku) {

            if (position != 0) {
                sku = sku_list.get(position).getSKU().get(0);
                sku_id = sku_list.get(position).getSKU_ID().get(0);
            }

        } else if (parent.getId() == R.id.sp_flasher) {

            if (position == 0) {
                price_flasher_available = -1;
            } else if (position == 1) {
                price_flasher_available = 1;
            } else if (position == 2) {
                price_flasher_available = 0;
            }
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    void clearBrandSpinner() {
        brand_list.clear();

        BrandMasterGetterSetter brand_select = new BrandMasterGetterSetter();
        String str = getResources().getString(R.string.select);
        brand_select.setBRAND(str);
        brand_select.setBRAND_ID("0");
        brand_list.add(0, brand_select);
        CustomBrandAdapter adapter = new CustomBrandAdapter(AdditionalPromoSKUwiseActivity.this, R.layout.custom_spinner_item, brand_list);

        spinner_brand_list.setAdapter(adapter);
        spinner_brand_list.setOnItemSelectedListener(this);
    }

    void clearSkuSpinner() {
        sku_list.clear();

        SkuMasterGetterSetter sku_select = new SkuMasterGetterSetter();
        String str = getResources().getString(R.string.select);
        sku_select.setSKU(str);
        sku_select.setSKU_ID("0");
        sku_list.add(0, sku_select);
        CustomSkuAdapter adapter = new CustomSkuAdapter(AdditionalPromoSKUwiseActivity.this, R.layout.custom_spinner_item, sku_list);

        spinner_sku_list.setAdapter(adapter);
        spinner_sku_list.setOnItemSelectedListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.fab) {

            boolean valid_flag = true;

            if (isExists) {
                if (added_promo_list.size() == 0) {
                    valid_flag = false;
                }
            }

            if (!valid_flag) {
                Snackbar.make(rec_added_promo, R.string.title_activity_Want_add, Snackbar.LENGTH_SHORT).show();
            } else if (isdata_added) {
                db.InsertPromoSKUwiseData(added_promo_list, categoryId, store_id, isExists);
                finish();
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            } else {
                finish();
            }

        } else if (id == R.id.fab_add) {

            discount = et_discount.getText().toString();
            price = et_price.getText().toString();

            if (sub_category.equals("")) {
                Snackbar.make(rec_added_promo, R.string.pls_select_sub_category, Snackbar.LENGTH_SHORT).show();
            } else if (brand.equals("")) {
                Snackbar.make(rec_added_promo, R.string.pls_select_brand, Snackbar.LENGTH_SHORT).show();
            } else if (sku.equals("")) {
                Snackbar.make(rec_added_promo, R.string.pls_select_sku, Snackbar.LENGTH_SHORT).show();
            } else if (price.equals("")) {
                Snackbar.make(rec_added_promo, R.string.pls_enter_price, Snackbar.LENGTH_SHORT).show();
            } else if (!price.equals("") && price.substring(0, 1).equals(".")) {
                Snackbar.make(rec_added_promo, R.string.incorrect_price, Snackbar.LENGTH_SHORT).show();
            } else if (is_camera_compulsory && img_str.equals("")) {
                Snackbar.make(rec_added_promo, R.string.click_image, Snackbar.LENGTH_SHORT).show();
            } else if (price_flasher_available == -1) {
                Snackbar.make(rec_added_promo, R.string.pls_select_price, Snackbar.LENGTH_SHORT).show();
            } else {
                PromoComplianceSkuwiseGetterSetter promo = new PromoComplianceSkuwiseGetterSetter();
                promo.setBrand(brand);
                promo.setBrand_id(brand_id);
                promo.setSub_category(sub_category);
                promo.setSub_category_id(sub_category_id);
                promo.setSku(sku);
                promo.setSku_id(sku_id);
                promo.setImg(img_str);
                promo.setDiscount_value(discount);
                promo.setPrice(price);
                promo.setPrice_flasher(price_flasher_available);
                added_promo_list.add(promo);

                rec_added_promo.setLayoutManager(new LinearLayoutManager(context));
                PromoAdapter gapAdapter = new PromoAdapter(added_promo_list);
                rec_added_promo.setAdapter(gapAdapter);

                sub_category = "";
                sub_category_id = "0";
                brand = "";
                brand_id = "0";
                sku = "";
                sku_id = "0";
                discount = "";
                price = "";
                img_str = "";
                price_flasher_available = -1;

                et_discount.setText("");
                et_price.setText("");
                spinner_sub_category_list.setSelection(0);
                clearBrandSpinner();
                clearSkuSpinner();
                sp_flasher.setSelection(0);

                if (is_camera_compulsory) {
                    img_cam.setBackgroundResource(R.drawable.camera_orange_star_green);
                } else {
                    img_cam.setBackgroundResource(R.mipmap.camera_orange);
                }

                isdata_added = true;
            }

        } else if (id == R.id.img_promotion_add) {

            _pathforcheck = "Additional_Promo_Skuwise_Image" + store_id + categoryId + visit_date.replace("/", "") + "_" + CommonFunctions.getCurrentTimeWithLanguage(context).replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;

            startCameraActivity(1);

        } else if (id == R.id.btntoggle) {

            isExists = btntoggle.isChecked();

            if (isExists) {
                lin_parent.setVisibility(View.VISIBLE);
                fab_add.show();
            } else {
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(AdditionalPromoSKUwiseActivity.this);
                builder.setTitle("Parinaam");
                builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                        .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                fab_add.hide();
                                added_promo_list.clear();

                                rec_added_promo.setLayoutManager(new LinearLayoutManager(context));
                                promoAdapter = new PromoAdapter(added_promo_list);
                                rec_added_promo.setAdapter(promoAdapter);

                                lin_parent.setVisibility(View.GONE);

                                sub_category = "";
                                sub_category_id = "0";
                                brand = "";
                                brand_id = "0";
                                sku = "";
                                sku_id = "0";
                                discount = "";
                                price = "";
                                img_str = "";

                                et_discount.setText("");
                                et_price.setText("");
                                spinner_sub_category_list.setSelection(0);
                                clearBrandSpinner();
                                clearSkuSpinner();

                                if (is_camera_compulsory) {
                                    img_cam.setBackgroundResource(R.drawable.camera_orange_star_green);
                                } else {
                                    img_cam.setBackgroundResource(R.mipmap.camera_orange);
                                }

                                isdata_added = true;
                            }
                        })
                        .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                btntoggle.setChecked(true);
                            }
                        });

                android.app.AlertDialog alert = builder.create();
                alert.show();
            }
        }
    }

    private void startCameraActivity(int pos) {
        try {

            Log.i("Stock & Facing ", "startCameraActivity()");
            File file = new File(_path);
            outputFileUri = FileProvider.getUriForFile(context, "cpm.com.gskmtorange.fileprovider", file);

            String defaultCameraPackage = "";
            final PackageManager packageManager = getPackageManager();
            List<ApplicationInfo> list = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
            for (int n = 0; n < list.size(); n++) {
                if ((list.get(n).flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
                  /*  Log.e("TAG", "Installed Applications  : " + list.get(n).loadLabel(packageManager).toString());
                    Log.e("TAG", "package name  : " + list.get(n).packageName);*/

                    //temp value in case camera is gallery app above jellybean
                    String packag = list.get(n).loadLabel(packageManager).toString();
                    if (packag.equalsIgnoreCase("Gallery") || packag.equalsIgnoreCase("Galeri") || packag.equalsIgnoreCase("الاستوديو")) {
                        gallery_package = list.get(n).packageName;
                    }

                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        if (packag.equalsIgnoreCase("Camera") || packag.equalsIgnoreCase("Kamera") || packag.equalsIgnoreCase("الكاميرا")) {
                            defaultCameraPackage = list.get(n).packageName;
                            break;
                        }
                    } else {

                        if (packag.equalsIgnoreCase("Camera") || packag.equalsIgnoreCase("Kamera") || packag.equalsIgnoreCase("الكاميرا")) {

                            defaultCameraPackage = list.get(n).packageName;
                            break;
                        }
                    }
                }
            }

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(defaultCameraPackage);
            //startActivityForResult(intent, 1);
            startActivityForResult(intent, pos);
            //startActivityForResult(intent, position);

        } catch (ActivityNotFoundException e) {
            e.printStackTrace();

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(gallery_package);
            //startActivityForResult(intent, 0);
            startActivityForResult(intent, pos);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.i("MakeMachine", "resultCode: " + resultCode);
        switch (resultCode) {
            case 0:
                Log.i("MakeMachine", "User cancelled");
                break;

            case -1:

                if (_pathforcheck != null && !_pathforcheck.equals("")) {
                    if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {

                        img_cam.setBackgroundResource(R.mipmap.camera_green);

                        img_str = _pathforcheck;
                        _pathforcheck = "";
                    }
                }

                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public class CustomBrandAdapter extends ArrayAdapter<String> {

        private Activity activity;
        private ArrayList data;
        BrandMasterGetterSetter tempValues = null;
        LayoutInflater inflater;

        /*************
         * CustomBrandAdapter Constructor
         *****************/
        public CustomBrandAdapter(AdditionalPromoSKUwiseActivity activitySpinner, int textViewResourceId, ArrayList objects

        ) {
            super(activitySpinner, textViewResourceId, objects);

            /********** Take passed values **********/
            activity = activitySpinner;
            data = objects;
            /***********  Layout inflator to call external xml layout () **********************/
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        // This funtion called for each row ( Called data.size() times )
        public View getCustomView(int position, View convertView, ViewGroup parent) {

            /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
            View row = inflater.inflate(R.layout.custom_spinner_item, parent, false);

            /***** Get each Model object from Arraylist ********/
            tempValues = null;
            tempValues = (BrandMasterGetterSetter) data.get(position);

            TextView label = (TextView) row.findViewById(R.id.tv_text);

            if (position == 0) {

                // Default selected Spinner item
                label.setText(getResources().getString(R.string.select));
                //sub.setText("");
            } else {
                // Set values for spinner each row
                label.setText(tempValues.getBRAND().get(0));
            }

            return row;
        }
    }

    public class CustomSkuAdapter extends ArrayAdapter<String> {

        private Activity activity;
        private ArrayList data;
        SkuMasterGetterSetter tempValues = null;
        LayoutInflater inflater;

        /*************
         * CustomSkuAdapter Constructor
         *****************/
        public CustomSkuAdapter(AdditionalPromoSKUwiseActivity activitySpinner, int textViewResourceId, ArrayList objects

        ) {
            super(activitySpinner, textViewResourceId, objects);

            /********** Take passed values **********/
            activity = activitySpinner;
            data = objects;
            /***********  Layout inflator to call external xml layout () **********************/
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        // This funtion called for each row ( Called data.size() times )
        public View getCustomView(int position, View convertView, ViewGroup parent) {

            /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
            View row = inflater.inflate(R.layout.custom_spinner_item, parent, false);

            /***** Get each Model object from Arraylist ********/
            tempValues = null;
            tempValues = (SkuMasterGetterSetter) data.get(position);

            TextView label = (TextView) row.findViewById(R.id.tv_text);

            if (position == 0) {

                // Default selected Spinner item
                label.setText(getResources().getString(R.string.select));
                //sub.setText("");
            } else {
                // Set values for spinner each row
                label.setText(tempValues.getSKU().get(0));
            }

            return row;
        }
    }

    public class CustomSubCategoryAdapter extends ArrayAdapter<String> {

        private Activity activity;
        private ArrayList data;
        MSL_AvailabilityStockFacingGetterSetter tempValues = null;
        LayoutInflater inflater;

        /*************
         * CustomSubCategoryAdapter Constructor
         *****************/
        public CustomSubCategoryAdapter(AdditionalPromoSKUwiseActivity activitySpinner, int textViewResourceId, ArrayList objects

        ) {
            super(activitySpinner, textViewResourceId, objects);

            /********** Take passed values **********/
            activity = activitySpinner;
            data = objects;
            /***********  Layout inflator to call external xml layout () **********************/
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        // This funtion called for each row ( Called data.size() times )
        public View getCustomView(int position, View convertView, ViewGroup parent) {

            /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
            View row = inflater.inflate(R.layout.custom_spinner_item, parent, false);

            /***** Get each Model object from Arraylist ********/
            tempValues = null;
            tempValues = (MSL_AvailabilityStockFacingGetterSetter) data.get(position);

            TextView label = (TextView) row.findViewById(R.id.tv_text);

            if (position == 0) {

                // Default selected Spinner item
                label.setText(getResources().getString(R.string.select));
                //sub.setText("");
            } else {
                // Set values for spinner each row
                label.setText(tempValues.getSub_category());
            }

            return row;
        }
    }

    public class PromoAdapter extends RecyclerView.Adapter<PromoAdapter.ViewHolder> {

        private ArrayList<PromoComplianceSkuwiseGetterSetter> list;

        public PromoAdapter(ArrayList<PromoComplianceSkuwiseGetterSetter> promoList) {
            list = promoList;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_added_promo, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {

            final PromoComplianceSkuwiseGetterSetter mItem = list.get(position);
            holder.tv_sub_category.setText(getString(R.string.sub_category) + " - " + mItem.getSub_category());
            holder.tv_brand.setText(getString(R.string.brand) + " - " + mItem.getBrand());
            holder.tv_sku.setText(getString(R.string.sku) + " - " + mItem.getSku());
            holder.tv_discount_val.setText(getString(R.string.discount_value) + " - " + mItem.getDiscount_value());
            holder.tv_price.setText(getString(R.string.price) + " - " + mItem.getPrice());
            String exists = "";
            if (mItem.getPrice_flasher() == 1) {
                exists = getString(R.string.yes);
            } else {
                exists = getString(R.string.no);
            }
            holder.tv_promo_flasher_exists.setText(" - " + exists);

        }

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

        public class ViewHolder extends RecyclerView.ViewHolder {
            public final View mView;
            public final TextView tv_sub_category, tv_brand, tv_sku, tv_discount_val, tv_price, tv_promo_flasher_exists;

            public ViewHolder(View view) {
                super(view);

                mView = view;

                tv_sub_category = (TextView) mView.findViewById(R.id.tv_sub_category);
                tv_brand = (TextView) mView.findViewById(R.id.tv_brand);
                tv_sku = (TextView) mView.findViewById(R.id.tv_sku);
                tv_discount_val = (TextView) mView.findViewById(R.id.tv_discount);
                tv_price = (TextView) mView.findViewById(R.id.tv_price);
                tv_promo_flasher_exists = (TextView) mView.findViewById(R.id.tv_promo_flasher_exists);


            }

        }
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        ischanged();
    }

    @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) {
            ischanged();
        }

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

        return super.onOptionsItemSelected(item);
    }

    void ischanged() {
        if (isdata_added) {
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(AdditionalPromoSKUwiseActivity.this);
            builder.setTitle("Parinaam");
            builder.setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                    finish();
                    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                }
            }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            android.app.AlertDialog alert = builder.create();
            alert.show();
        } else {
            super.onBackPressed();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

    public class CustomSpinnerAdapter extends ArrayAdapter<String> {

        SelectGetterSetter tempValues = null;
        LayoutInflater inflater;
        private Activity activity;
        private ArrayList data;

        /*************
         * CustomAdapter Constructor
         *****************/
        public CustomSpinnerAdapter(AdditionalPromoSKUwiseActivity activitySpinner, int textViewResourceId, ArrayList objects

        ) {
            super(activitySpinner, textViewResourceId, objects);

            /********** Take passed values **********/
            activity = activitySpinner;
            data = objects;
            /***********  Layout inflator to call external xml layout () **********************/
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        // This funtion called for each row ( Called data.size() times )
        public View getCustomView(int position, View convertView, ViewGroup parent) {

            /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
            View row = inflater.inflate(R.layout.custom_spinner_item, parent, false);

            /***** Get each Model object from Arraylist ********/
            tempValues = null;
            tempValues = (SelectGetterSetter) data.get(position);

            TextView label = (TextView) row.findViewById(R.id.tv_text);

            if (position == 0) {

                // Default selected Spinner item
                label.setText(getString(R.string.select));
                //sub.setText("");
            } else {
                // Set values for spinner each row
                label.setText(tempValues.getAns());
            }

            return row;
        }
    }
}
