package com.cpm.lorealbaautomation.dailyactivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;

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

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.download.Downloader;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterNonVisibility;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterPosm;

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

import static com.cpm.lorealbaautomation.constant.CommonFunctions.getCurrentTime;
import static com.cpm.lorealbaautomation.dailyactivity.StoreImageActivity.convertBitmap;

public class VisibilityElimentsActivity extends AppCompatActivity implements View.OnClickListener {
    String visit_date, username, str_promotion_img = "", _pathforcheck, _path, counterId;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor = null;
    ArrayList<MasterPosm> visibilityElementList = new ArrayList<>();
    RecyclerView drawer_layout_recycle_store;
    ValueAdapter adapter;
    FloatingActionButton fab;
    int _currectposition = -1;
    Lorealba_Database db;
    Context context;
    Dialog dialog1;
    WebView webview;
    ImageView img_main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_visibility_eliments);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        uivalidate();
        validateAdapterData();
    }


    void validateAdapterData() {
        db.open();
        visibilityElementList = db.getVisibility_inserted_data(counterId, visit_date,null,false);
        if (visibilityElementList.size() == 0) {
            db.open();
            visibilityElementList = db.getVisibility_master_data(counterId);
        } else {
            fab.hide();
        }

        if (visibilityElementList.size() > 0) {
            adapter = new ValueAdapter(context, visibilityElementList);
            drawer_layout_recycle_store.setAdapter(adapter);
            drawer_layout_recycle_store.setLayoutManager(new LinearLayoutManager(context));
        }

    }

    private void uivalidate() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        drawer_layout_recycle_store = (RecyclerView) findViewById(R.id.drawer_layout_recycle_store);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        setSupportActionBar(toolbar);

        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(getString(R.string.visibility) + " - " + visit_date);
        fab.setOnClickListener(this);

        drawer_layout_recycle_store.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (dy > 0)
                    fab.hide();
                else if (dy < 0)
                    fab.show();
            }
        });
    }


    @Override
    public void onClick(final View v) {
        if (v.getId() == R.id.fab) {
            if (validate_condition(visibilityElementList)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData);
                builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        db.open();
                        db.insertVisibility_data(username, counterId, visit_date, visibilityElementList, CommonFunctions.getUUID(context));
                        dialogInterface.dismiss();

                        //upload service
                        Intent intent = new Intent(context, Downloader.class);
                        db.open();
                        ArrayList<MasterPosm> arrayList = db.getVisibility_inserted_data(counterId, visit_date, null, false);
                        if (arrayList.size() > 0) {
                            intent.putExtra(CommonString.KEY_VisibilityEliment, arrayList);
                            Downloader.enqueueWork(context, intent);
                        }

                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        finish();


                    }
                });
                builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });
                builder.show();
            }
        }

    }

    public class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
        private LayoutInflater inflator;
        List<MasterPosm> data;

        public ValueAdapter(Context context, List<MasterPosm> data) {
            inflator = LayoutInflater.from(context);
            this.data = data;
        }

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

        @Override
        public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            final MasterPosm current = data.get(position);
            holder.promotion_name.setText(current.getPosm());
            holder.promotion_name.setTypeface(Typeface.create("sans-serif-thin", Typeface.BOLD));
            holder.promotion_name.setId(position);

            if (!current.getPromotion_exists_state().equals("") && current.getPromotion_exists_state().equalsIgnoreCase("Yes")) {
                current.setPromotion_exists_state("Yes");
                holder.rl_child_promotion.setVisibility(View.VISIBLE);
                holder.rl_child_promotion.setId(position);
                holder.promotion_rl_non.setVisibility(View.GONE);
                holder.promotion_rl_non.setId(position);
                holder.promotion_btn_first.setBackgroundColor(getResources().getColor(R.color.green));
                holder.promotion_btn_first.setTextColor(getResources().getColor(R.color.white));
                holder.promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.rouded_corner_pinki));
                holder.promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login));
                current.setPromotion_currect_ans_Id("0");
                current.setPromotion_currect_ans("");
                holder.promotion_spin.setSelection(0);
            } else if (!current.getPromotion_exists_state().equals("") && current.getPromotion_exists_state().equalsIgnoreCase("No")) {
                current.setPromotion_exists_state("No");
                holder.rl_child_promotion.setVisibility(View.GONE);
                holder.rl_child_promotion.setId(position);
                holder.promotion_rl_non.setVisibility(View.VISIBLE);
                holder.promotion_rl_non.setId(position);
                holder.promotion_btn_second.setBackgroundColor(getResources().getColor(R.color.red));
                holder.promotion_btn_second.setTextColor(getResources().getColor(R.color.white));
                holder.promotion_btn_first.setBackgroundDrawable(getResources().getDrawable(R.drawable.rouded_corner_pinki));
                holder.promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login));

                holder.img_promotion.setImageResource(R.mipmap.camera_bs);
                holder.img_promotion.setId(position);
                current.setPromotion_img("");
            }


            holder.promotion_btn_first.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    current.setPromotion_exists_state("Yes");
                    holder.rl_child_promotion.setVisibility(View.VISIBLE);
                    holder.rl_child_promotion.setId(position);
                    holder.promotion_rl_non.setVisibility(View.GONE);
                    holder.promotion_rl_non.setId(position);
                    holder.promotion_btn_first.setBackgroundColor(getResources().getColor(R.color.green));
                    holder.promotion_btn_first.setTextColor(getResources().getColor(R.color.white));
                    holder.promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.rouded_corner_pinki));
                    holder.promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login));
                    current.setPromotion_currect_ans_Id("0");
                    current.setPromotion_currect_ans("");
                    holder.promotion_spin.setSelection(0);
                }
            });

            holder.promotion_btn_second.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    current.setPromotion_exists_state("No");
                    holder.rl_child_promotion.setVisibility(View.GONE);
                    holder.rl_child_promotion.setId(position);
                    holder.promotion_rl_non.setVisibility(View.VISIBLE);
                    holder.promotion_rl_non.setId(position);

                    holder.promotion_btn_second.setBackgroundColor(getResources().getColor(R.color.red));
                    holder.promotion_btn_second.setTextColor(getResources().getColor(R.color.white));
                    holder.promotion_btn_first.setBackgroundDrawable(getResources().getDrawable(R.drawable.rouded_corner_pinki));
                    holder.promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login));

                    holder.img_promotion.setImageResource(R.mipmap.camera_bs);
                    holder.img_promotion.setId(position);
                    current.setPromotion_img("");

                }
            });

            holder.img_promotion.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    _currectposition = position;
                    _pathforcheck = counterId + "_" + current.getPosmId().toString() + "_visibility_img_" + getCurrentTime().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
                }
            });

            if (!str_promotion_img.equals("")) {
                if (_currectposition == position) {
                    current.setPromotion_img(str_promotion_img);
                    str_promotion_img = "";
                }
            }

            if (!current.getPromotion_img().equals("")) {
                holder.img_promotion.setImageResource(R.mipmap.camera_bsd);
                holder.img_promotion.setId(position);
            } else {
                holder.img_promotion.setImageResource(R.mipmap.camera_bs);
                holder.img_promotion.setId(position);
            }


            //for reason spinner
            final ArrayList<MasterNonVisibility> reason_list = db.getnon_promotion_reasonList();
            MasterNonVisibility non = new MasterNonVisibility();
            non.setReason("- Select -");
            non.setReasonId(0);
            reason_list.add(0, non);

            holder.promotion_spin.setAdapter(new ReasonSpinnerAdapter(context, R.layout.spinner_text_view, reason_list));

            for (int i = 0; i < reason_list.size(); i++) {
                if (reason_list.get(i).getReasonId().toString().equals(current.getPromotion_currect_ans_Id())) {
                    holder.promotion_spin.setSelection(i);
                    break;
                }
            }

            holder.promotion_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    if (pos != 0) {
                        MasterNonVisibility ans = reason_list.get(pos);
                        current.setPromotion_currect_ans(ans.getReason());
                        current.setPromotion_currect_ans_Id(ans.getReasonId().toString());
                    } else {
                        current.setPromotion_currect_ans("");
                        current.setPromotion_currect_ans_Id("0");
                    }
                }

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

            holder.reference_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (current.getRefImage() != null && !current.getRefImage().equals("")) {
                        popup(current.getRefImage());
                    } else {
                        AlertandMessages.showToastMsg(context, "Promo Reference image not found");
                    }
                }
            });
        }


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

        class MyViewHolder extends RecyclerView.ViewHolder {
            ImageView img_promotion;
            // TextView promotion_name, start_date, end_date, reference_img;
            TextView promotion_name, reference_img;
            LinearLayout promotion_rl_non, rl_child_promotion;
            Button promotion_btn_first, promotion_btn_second;
            Spinner promotion_spin;

            public MyViewHolder(View itemView) {
                super(itemView);
                promotion_rl_non = (LinearLayout) itemView.findViewById(R.id.promotion_rl_non);
                rl_child_promotion = (LinearLayout) itemView.findViewById(R.id.rl_child_promotion);
                promotion_spin = (Spinner) itemView.findViewById(R.id.promotion_spin);
                promotion_btn_first = (Button) itemView.findViewById(R.id.posm_btn_first);
                promotion_btn_second = (Button) itemView.findViewById(R.id.posm_btn_second);
                img_promotion = (ImageView) itemView.findViewById(R.id.img_promotion);
                promotion_name = (TextView) itemView.findViewById(R.id.posm_name);
                reference_img = (TextView) itemView.findViewById(R.id.reference_img);

            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case 0:
                Log.i("MakeMachine", "User cancelled");
                break;
            case -1:
                if (_pathforcheck != null && !_pathforcheck.equals("")) {
                    try {
                        if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                            convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);
                            str_promotion_img = _pathforcheck;
                            adapter.notifyDataSetChanged();
                            _pathforcheck = "";
                        }

                    } catch (Exception e) {
                        e.fillInStackTrace();
                    }
                }
                break;
        }

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

    public class ReasonSpinnerAdapter extends ArrayAdapter<MasterNonVisibility> {
        List<MasterNonVisibility> list;
        Context context;
        int resourceId;

        public ReasonSpinnerAdapter(Context context, int resourceId, ArrayList<MasterNonVisibility> list) {
            super(context, resourceId, list);
            this.context = context;
            this.list = list;
            this.resourceId = resourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            LayoutInflater inflater = getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);
            MasterNonVisibility cm = list.get(position);
            TextView txt_spinner = (TextView) view.findViewById(R.id.txt_sp_text);
            txt_spinner.setText(list.get(position).getReason());

            return view;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            LayoutInflater inflater = getLayoutInflater();
            view = inflater.inflate(resourceId, parent, false);
            MasterNonVisibility cm = list.get(position);
            TextView txt_spinner = (TextView) view.findViewById(R.id.txt_sp_text);
            txt_spinner.setText(cm.getReason());

            return view;
        }

    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(CommonString.ONBACK_ALERT_MESSAGE)
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        finish();
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }


    private boolean validate_condition(ArrayList<MasterPosm> promotionList) {
        boolean status = true;
        for (int k = 0; k < promotionList.size(); k++) {
            MasterPosm object = promotionList.get(k);
            if (!object.getPromotion_exists_state().equals("")) {
                if (object.getPromotion_exists_state().equalsIgnoreCase("Yes")) {
                    if (object.getPromotion_img().equals("")) {
                        showTost("Please capture " + object.getPosm() + " image_icon.");
                        status = false;
                        break;
                    }
                } else {
                    if (object.getPromotion_currect_ans_Id().equals("0")) {
                        showTost("Please Select reason of " + object.getPosm() + ".");
                        status = false;
                        break;
                    }
                }
            } else {
                //  showTost("Please Click Exists of " + object.getPromotionName() + ".");
                showTost("Please Click Exists of " + object.getPosm() + ".");
                status = false;
            }
        }
        return status;
    }

    void showTost(String msg) {
        AlertandMessages.showToastMsg(context, msg);
    }

    public class MultiPurposeDialog extends Dialog {
        public MultiPurposeDialog(Context context) {
            super(context);
            // DIALOG USER_INTERFACE TEMPLATE
            WindowManager.LayoutParams wmLayoutParams = getWindow().getAttributes();
            wmLayoutParams.gravity = Gravity.CENTER;
            getWindow().setAttributes(wmLayoutParams);
            setTitle(null);
            setCancelable(false);
            setOnCancelListener(null);
            LinearLayout layout = new LinearLayout(context);
            layout.setOrientation(LinearLayout.VERTICAL);
        }
    }

    private void popup(final String window_image) {
        dialog1 = new Dialog(VisibilityElimentsActivity.this);
        dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog1.setContentView(R.layout.dialog_refrence_image);
        webview = (WebView) dialog1.findViewById(R.id.webview);
        img_main = (ImageView) dialog1.findViewById(R.id.img_main);
        // dialog1.setCancelable(false);
        dialog1.setCanceledOnTouchOutside(true);
        db.open();

        webview.setWebViewClient(new MyWebViewClient());


        webview.getSettings().setJavaScriptEnabled(true);
        if (window_image != null) {
            webview.loadUrl(window_image);
        }

        dialog1.show();
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            //     img_main.setVisibility(View.VISIBLE);
            webview.setVisibility(View.VISIBLE);
            super.onPageFinished(view, url);
            view.clearCache(true);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            super.onPageStarted(view, url, favicon);
        }

    }

    @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) {
            super.onBackPressed();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }


        return super.onOptionsItemSelected(item);
    }


}