package cpm.com.gskmtorange.dailyentry;

import android.app.Activity;
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.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
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.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.CompetitonPromoGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.PROMOTION_TYPE_MASTERGetterSetter;

public class CompetitionPromoActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {
    private Context context;
    ToggleButton btntoggle;
    boolean isDataAdded = false, isExists = true, is_camera_compulsory = false;
    LinearLayout lin_parent;
    GSKOrangeDB db;
    private SharedPreferences preferences;
    Spinner spinner_brand_list,sp_promotion_typ,sp_subcategory;
    String store_id, visit_date, username, country_id,keyAccount_id,class_id,storeType_id;
    String categoryName, categoryId;
    ArrayList<BrandMasterGetterSetter> brand_list = new ArrayList<>();
    ArrayList<BrandMasterGetterSetter> subcategory_list = new ArrayList<>();
    ArrayList<PROMOTION_TYPE_MASTERGetterSetter> promotion_list = new ArrayList<>();
    String brand = "",subcategory="", _path = "";
    String promotion = "";
    EditText et_sku_name;
    FloatingActionButton fab_save, fab_add;
    ImageView imgCam, imgCam1, imgCam2;
    String img_str = "", img_str1 = "", img_str2 = "";
    String _pathforcheck, _pathforcheck1, _pathforcheck2;
    Uri outputFileUri;
    String gallery_package = "";
    boolean editFlag = false, isdata_added = false;
    String str, skuName;
    int brand_id = 0;
    int subcategoryId = 0;
    int promotion_id = 0;
    RecyclerView rec_added_counterfeit_product;
    ArrayList<CompetitonPromoGetterSetter> addedCounterfeitProducts = new ArrayList<>();
    ArrayList<CompetitonPromoGetterSetter> exists_data = new ArrayList<>();
    private  LinearLayout lay_competitor_name;

    ProductAdapter productAdapter;

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        btntoggle = (ToggleButton) findViewById(R.id.btntoggle);
        lin_parent = (LinearLayout) findViewById(R.id.lin_parent_promo);
        et_sku_name = (EditText) findViewById(R.id.et_sku_name);
        sp_subcategory = (Spinner) findViewById(R.id.sp_subcategory);
        spinner_brand_list = (Spinner) findViewById(R.id.sp_brand);
        sp_promotion_typ = (Spinner) findViewById(R.id.sp_promotion_typ);
        lay_competitor_name = (LinearLayout) findViewById(R.id.lay_competitor_name);
        rec_added_counterfeit_product = (RecyclerView) findViewById(R.id.rec_added_counterfeit_product);

        //fab
        fab_save = findViewById(R.id.fab);
        fab_add = findViewById(R.id.fab_add);

        //camera Images
        imgCam = (ImageView) findViewById(R.id.img_cam);
        imgCam1 = (ImageView) findViewById(R.id.img_cam1);
        imgCam2 = (ImageView) findViewById(R.id.img_cam2);
        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);


        keyAccount_id = preferences.getString(CommonString.KEY_KEYACCOUNT_ID, "");
        class_id = preferences.getString(CommonString.KEY_CLASS_ID, "");
        storeType_id = preferences.getString(CommonString.KEY_STORETYPE_ID, "");


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

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

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

        btntoggle.setOnClickListener(this);
        fab_save.setOnClickListener(this);
        fab_add.setOnClickListener(this);
        imgCam.setOnClickListener(this);
        imgCam1.setOnClickListener(this);
        imgCam2.setOnClickListener(this);

        promotion_list = db.getPromotionTypeData();
        subcategory_list = db.getSubcategoryData(keyAccount_id, storeType_id,class_id,categoryId);

        //subcategory data
        BrandMasterGetterSetter subcategory_select = new BrandMasterGetterSetter();
        String subcat_select = getResources().getString(R.string.select);
        subcategory_select.setSUB_CATEGORY(subcat_select);
        subcategory_select.setSUB_CATEGORY_ID("0");
        subcategory_list.add(0, subcategory_select);
        CustomSubcategoryAdapter subcat_adapter = new CustomSubcategoryAdapter(CompetitionPromoActivity.this, R.layout.custom_spinner_item, subcategory_list);
        sp_subcategory.setAdapter(subcat_adapter);
        sp_subcategory.setOnItemSelectedListener(this);


        /*//brand data
        BrandMasterGetterSetter brand_select = new BrandMasterGetterSetter();
        String select = getResources().getString(R.string.select);
        brand_select.setBRAND(select);
        brand_select.setBRAND_ID("0");
        brand_list.add(0, brand_select);
        CustomBrandAdapter adapter = new CustomBrandAdapter(CompetitionPromoActivity.this, R.layout.custom_spinner_item, brand_list);
        spinner_brand_list.setAdapter(adapter);
        spinner_brand_list.setOnItemSelectedListener(this);*/

        //competitor
        PROMOTION_TYPE_MASTERGetterSetter promoType_select = new PROMOTION_TYPE_MASTERGetterSetter();
        String selectcomp = getResources().getString(R.string.select);
        promoType_select.setPROMOTION_TYPE(selectcomp);
        promoType_select.setPROMOTION_TYPE_ID("0");
        promotion_list.add(0, promoType_select);
        CustomPromotionTypeAdapter comp_adapter = new CustomPromotionTypeAdapter(CompetitionPromoActivity.this, R.layout.custom_spinner_item, promotion_list);
        sp_promotion_typ.setAdapter(comp_adapter);
        sp_promotion_typ.setOnItemSelectedListener(this);




        //Product List
        exists_data = db.getCompetitionPromoExistsAfterData(store_id, categoryId);

        if(exists_data.size()>0){
            isExists = exists_data.get(0).isExists();
            if(exists_data.get(0).isExists()){
                addedCounterfeitProducts = db.getCometionPromoAfterData(store_id, categoryId);
                if(addedCounterfeitProducts.size()>0){
                    rec_added_counterfeit_product.setLayoutManager(new LinearLayoutManager(context));
                    productAdapter = new ProductAdapter(addedCounterfeitProducts);
                    rec_added_counterfeit_product.setAdapter(productAdapter);
                }
            }
            else {
                //fab_add.hide();//.setVisibility(View.GONE);
                addedCounterfeitProducts.clear();
                lin_parent.setVisibility(View.GONE);
            }
        }

        btntoggle.setChecked(isExists);

        str = CommonString.getImagesFolder(context);
    }

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

        if (id == R.id.btntoggle) {
            isExists = btntoggle.isChecked();

            if (isExists) {
                lin_parent.setVisibility(View.VISIBLE);
                isdata_added = true;
            } else {
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(CompetitionPromoActivity.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) {

                                lin_parent.setVisibility(View.GONE);

                                brand = "";
                                subcategory = "";
                                promotion = "";
                                brand_id = 0;
                                subcategoryId = 0;
                                promotion_id = 0;
                                skuName = "";
                                img_str = "";
                                img_str1 = "";
                                img_str2 = "";
                                et_sku_name.setText("");
                                sp_subcategory.setSelection(0);
                                spinner_brand_list.setSelection(0);
                                sp_promotion_typ.setSelection(0);

                                addedCounterfeitProducts.clear();
                                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();
            }

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

            skuName = et_sku_name.getText().toString().replaceAll("[&^<>{}'$]", "").replaceFirst("^0+(?!$)", "");

            if (promotion.equals("")) {
                Snackbar.make(rec_added_counterfeit_product, R.string.pls_select_promo_type, Snackbar.LENGTH_SHORT).show();
            } else if (subcategory.equals("")) {
                Snackbar.make(rec_added_counterfeit_product, R.string.pls_select_sub_category, Snackbar.LENGTH_SHORT).show();
            } else if (brand.equals("")) {
                Snackbar.make(rec_added_counterfeit_product, R.string.pls_select_competitor, Snackbar.LENGTH_SHORT).show();
            } else if (skuName.equals("")) {
                Snackbar.make(rec_added_counterfeit_product, R.string.pls_enter_comment, Snackbar.LENGTH_SHORT).show();
            } else {
                CompetitonPromoGetterSetter product = new CompetitonPromoGetterSetter();
                product.setBrand(brand);
                product.setPromotion(promotion);
                product.setBrandId(brand_id);
                product.setPromotion_id(promotion_id);
                product.setSkuName(skuName);
                product.setImgStr(img_str);
                product.setImgStr1(img_str1);
                product.setImgStr2(img_str2);

                addedCounterfeitProducts.add(product);

                rec_added_counterfeit_product.setLayoutManager(new LinearLayoutManager(context));
                productAdapter = new ProductAdapter(addedCounterfeitProducts);
                rec_added_counterfeit_product.setAdapter(productAdapter);

                subcategory = "";
                brand = "";
                promotion = "";
                subcategoryId = 0;
                brand_id = 0;
                promotion_id = 0;
                skuName = "";
                img_str = "";
                img_str1 = "";
                img_str2 = "";
                et_sku_name.setText("");
                sp_subcategory.setSelection(0);
                spinner_brand_list.setSelection(0);
                sp_promotion_typ.setSelection(0);

                imgCam.setBackgroundResource(R.mipmap.camera_orange);
                imgCam1.setBackgroundResource(R.mipmap.camera_orange);
                imgCam2.setBackgroundResource(R.mipmap.camera_orange);

                isdata_added = true;
            }

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

            if (isExists && addedCounterfeitProducts.size() == 0) {
                Snackbar.make(rec_added_counterfeit_product, R.string.title_activity_Want_add, Snackbar.LENGTH_SHORT).show();
            } else {
                db.InsertComptionPromotData(addedCounterfeitProducts, categoryId, store_id, isExists);
                finish();
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            }

        } else if (id == R.id.img_cam) {
            _pathforcheck = store_id + "CounterfeitProductImg1" + categoryId + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeWithLanguage(context).replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            startCameraActivity();

        } else if (id == R.id.img_cam1) {
            _pathforcheck1 = store_id + "CounterfeitProductImg2" + categoryId + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeWithLanguage(context).replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck1;
            startCameraActivity();

        } else if (id == R.id.img_cam2) {
            _pathforcheck2 = store_id + "CounterfeitProductImg3" + categoryId + visit_date.replace("/", "") + CommonFunctions.getCurrentTimeWithLanguage(context).replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck2;
            startCameraActivity();
        }


    }

    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(CompetitionPromoActivity.this, R.layout.custom_spinner_item, brand_list);

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

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

        if (id == R.id.sp_subcategory) {
            if (position != 0) {
                subcategory = subcategory_list.get(position).getSUB_CATEGORY().get(0);
                subcategoryId = Integer.parseInt(subcategory_list.get(position).getSUB_CATEGORY_ID().get(0));

                brand_list = db.getCompetionData(keyAccount_id, storeType_id, class_id, categoryId, subcategoryId);

                // Prepare brand data with default "Select" option
                BrandMasterGetterSetter brand_select = new BrandMasterGetterSetter();
                String select = getResources().getString(R.string.select);
                brand_select.setBRAND(select);
                brand_select.setBRAND_ID("0");
                brand_list.add(0, brand_select);

                CustomBrandAdapter adapter = new CustomBrandAdapter(CompetitionPromoActivity.this, R.layout.custom_spinner_item, brand_list);
                spinner_brand_list.setAdapter(adapter);
                spinner_brand_list.setOnItemSelectedListener(this);

                lay_competitor_name.setVisibility(View.VISIBLE);
            } else {
                subcategory = "";
                subcategoryId = 0;
                lay_competitor_name.setVisibility(View.GONE);
            }
        } else if (id == R.id.sp_brand) {
            if (position != 0) {
                brand = brand_list.get(position).getBRAND().get(0);
                brand_id = Integer.parseInt(brand_list.get(position).getBRAND_ID().get(0));
            } else {
                brand = "";
                brand_id = 0;
            }
        } else if (id == R.id.sp_promotion_typ) {
            if (position != 0) {
                promotion = promotion_list.get(position).getPROMOTION_TYPE().get(0);
                promotion_id = Integer.parseInt(promotion_list.get(position).getPROMOTION_TYPE_ID().get(0));
            } else {
                promotion = "";
                promotion_id = 0;
            }
        }


    }

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

    }

    //subcategory data
    public class CustomSubcategoryAdapter extends ArrayAdapter<String> {

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

        /*************
         * CustomSubcategoryAdapter Constructor
         *****************/
        public CustomSubcategoryAdapter(
                CompetitionPromoActivity 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.getSUB_CATEGORY().get(0));
            }

            return row;
        }
    }



    public class CustomBrandAdapter extends ArrayAdapter<String> {

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

        /*************
         * CustomBrandAdapter Constructor
         *****************/
        public CustomBrandAdapter(
                CompetitionPromoActivity 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 CustomPromotionTypeAdapter extends ArrayAdapter<String> {

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

        /*************
         * CustomPromotionTypeAdapter Constructor
         *****************/
        public CustomPromotionTypeAdapter(
                CompetitionPromoActivity 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 = (PROMOTION_TYPE_MASTERGetterSetter) 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.getPROMOTION_TYPE().get(0));
            }

            return row;
        }
    }

    protected void startCameraActivity() {
        try {

            Log.i("MakeMachine", "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 (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;
                        }
                    }
                }
            }

            //com.android.gallery3d

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.setPackage(defaultCameraPackage);
            startActivityForResult(intent, 0);
        } 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);

        } 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:

                editFlag = true;

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

                        imgCam.setBackgroundResource(R.mipmap.camera_green);

                        img_str = _pathforcheck;
                        _pathforcheck = "";
                    }
                }

                if (_pathforcheck1 != null && !_pathforcheck1.equals("")) {
                    if (new File(str + _pathforcheck1).exists()) {

                        imgCam1.setBackgroundResource(R.mipmap.camera_green);

                        img_str1 = _pathforcheck1;
                        _pathforcheck1 = "";
                    }
                }
                if (_pathforcheck2 != null && !_pathforcheck2.equals("")) {
                    if (new File(str + _pathforcheck2).exists()) {

                        imgCam2.setBackgroundResource(R.mipmap.camera_green);

                        img_str2 = _pathforcheck2;
                        _pathforcheck2 = "";
                    }
                }


                break;
        }

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

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

        private ArrayList<CompetitonPromoGetterSetter> list;

        public ProductAdapter(ArrayList<CompetitonPromoGetterSetter> promoList) {
            list = promoList;
        }

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

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

            final CompetitonPromoGetterSetter mItem = list.get(position);
            holder.tv_brand.setText(getString(R.string.promotion_type) + " - " + mItem.getPromotion());
            holder.tv_competitor.setText(getString(R.string.competitor) + " - " + mItem.getBrand());
            holder.tv_sku_name.setText(getString(R.string.comment) + " - " + mItem.getSkuName());

        }

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

        public class ViewHolder extends RecyclerView.ViewHolder {
            public final View mView;
            public final TextView tv_brand, tv_competitor,tv_sku_name;

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

                mView = view;
                tv_brand = (TextView) mView.findViewById(R.id.tv_brand);
                tv_sku_name = (TextView) mView.findViewById(R.id.tv_sku_name);
                tv_competitor = (TextView) mView.findViewById(R.id.tv_competitor);

            }

        }
    }

    @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(CompetitionPromoActivity.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);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ischanged();
    }
}
