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.SpinnerAdapter;
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.CounterfeitProductGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.CounterfeitProductGetterSetter;

public class CounterfeitProductsActivity 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;
    String store_id, visit_date, username, country_id;
    String categoryName, categoryId;
    ArrayList<BrandMasterGetterSetter> brand_list = new ArrayList<>();
    String brand = "", _path = "";
    EditText et_stock, 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, stock = "";
    int brand_id = 0;
    RecyclerView rec_added_counterfeit_product;
    ArrayList<CounterfeitProductGetterSetter> addedCounterfeitProducts = new ArrayList<>();
    ArrayList<CounterfeitProductGetterSetter> exists_data = new ArrayList<>();
    ProductAdapter productAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counterfeit_products);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = this;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        btntoggle = (ToggleButton) findViewById(R.id.btntoggle);
        lin_parent = (LinearLayout) findViewById(R.id.lin_parent_promo);
        et_stock = (EditText) findViewById(R.id.et_stock);
        et_sku_name = (EditText) findViewById(R.id.et_sku_name);
        spinner_brand_list = (Spinner) findViewById(R.id.sp_brand);
        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);

        //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);

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

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

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

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

       // brand_list = db.getBrandMasterData(store_id, categoryId);
        brand_list = db.getBrandMasterData(store_id, categoryId);
        //brand_list = db.getBrandData(categoryId);

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

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

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

        if(exists_data.size()>0){
            isExists = exists_data.get(0).isExists();
            if(exists_data.get(0).isExists()){
                addedCounterfeitProducts = db.getCounterfeitProductAfterData(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(CounterfeitProductsActivity.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 = "";
                                brand_id = 0;

                                stock = "";
                                skuName = "";
                                img_str = "";
                                img_str1 = "";
                                img_str2 = "";

                                et_stock.setText("");
                                et_sku_name.setText("");
                                spinner_brand_list.setSelection(0);

                                addedCounterfeitProducts.clear();
                                isdata_added = true;
                            }
                        })
                        .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //checkBox.setChecked(true);
                                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+(?!$)", "");
            stock = et_stock.getText().toString();

            if (brand.equals("")) {
                Snackbar.make(rec_added_counterfeit_product, R.string.pls_select_brand, Snackbar.LENGTH_SHORT).show();
            } else if (stock.equals("")) {
                Snackbar.make(rec_added_counterfeit_product, R.string.pls_enter_stock, Snackbar.LENGTH_SHORT).show();
            } else if (skuName.equals("")) {
                Snackbar.make(rec_added_counterfeit_product, R.string.pls_enter_sku, Snackbar.LENGTH_SHORT).show();
            } else if (img_str.equals("") && img_str1.equals("") && img_str2.equals("")) {
                Snackbar.make(rec_added_counterfeit_product, R.string.click_image, Snackbar.LENGTH_SHORT).show();
            } else {
                CounterfeitProductGetterSetter product = new CounterfeitProductGetterSetter();
                product.setBrand(brand);
                product.setBrandId(brand_id);
                product.setStock(Integer.parseInt(stock));
                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);

                brand = "";
                brand_id = 0;

                stock = "";
                skuName = "";
                img_str = "";
                img_str1 = "";
                img_str2 = "";

                et_stock.setText("");
                et_sku_name.setText("");
                spinner_brand_list.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.InsertCounterfeitProductData(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(CounterfeitProductsActivity.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 id) {
        if (parent.getId() == 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;
            }
        }


    }

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

    }

    public class CustomBrandAdapter extends ArrayAdapter<String> {

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

        /*************
         * CustomBrandAdapter Constructor
         *****************/
        public CustomBrandAdapter(
                CounterfeitProductsActivity 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;
        }
    }

    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 (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;
                        }
                    }
                }
            }

            //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<CounterfeitProductGetterSetter> list;

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

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

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

            final CounterfeitProductGetterSetter mItem = list.get(position);
            holder.tv_brand.setText(getString(R.string.brand) + " - " + mItem.getBrand());
            holder.tv_sku_name.setText(getString(R.string.skuname) + " - " + mItem.getSkuName());
            holder.tv_stock.setText(" - " + mItem.getStock());

        }

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

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

            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_stock = (TextView) mView.findViewById(R.id.tv_stock);

            }

        }
    }

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