package com.cpm.lorealbaautomation.breakmanagement;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

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.Button;
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.MasterBreak;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class BreakManagementActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    ArrayList<MasterBreak> breakmanageList = new ArrayList<>();
    ArrayList<MasterBreak> insertedBreakList = new ArrayList<>();
    MasterBreak masterBreakObject = new MasterBreak();
    ArrayAdapter<CharSequence> break_managemntAdapter;
    String CounterId, visit_date, username, loginTym = "", breakType = "", breakId = "0", startTym = "", endTym = "";
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor = null;
    Button promotion_btn_first, promotion_btn_second;
    TextView txt_login_Tym, txt_start_Tym;
    RecyclerView recycl_break_managemnt;
    Spinner spin_break_Type;
    boolean clicked_flag = false, flag_update = false;
    Lorealba_Database db;
    AlertDialog.Builder alert;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_break_management);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        iduserinterface();
        setTitle("Break Management -" + username);
        ////update device time from server time.............
        if (CommonFunctions.checkNetIsAvailable(context)) {
            CommonFunctions.GetServerTym(context, username, db);
        }
    }


    @SuppressLint("SetTextI18n")
    private void iduserinterface() {
        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, "");
        txt_login_Tym = (TextView) findViewById(R.id.txt_login_Tym);
        txt_start_Tym = (TextView) findViewById(R.id.txt_start_Tym);
        spin_break_Type = (Spinner) findViewById(R.id.spin_break_Type);
        //for demo btn
        promotion_btn_first = (Button) findViewById(R.id.posm_btn_first);
        promotion_btn_second = (Button) findViewById(R.id.posm_btn_second);
        recycl_break_managemnt = (RecyclerView) findViewById(R.id.recycl_break_managemnt);

        promotion_btn_first.setOnClickListener(this);
        promotion_btn_second.setOnClickListener(this);
        db.open();
        loginTym = db.get_baLoginTym(visit_date, username).getUserLoginTym();
        loginTym = CommonFunctions.setTimeFormat(loginTym);
        txt_login_Tym.setText("Login Time - " + loginTym);
        calculate_spin();
        db.open();
        calcalate_list_data(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        db.open();
    }

    @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
    private void calcalate_list_data(boolean flag) {
        db.open();
        insertedBreakList = db.getBreakManagementList(CounterId, visit_date, username, null);
        if (insertedBreakList.size() > 0) {
            for (int k = 0; k < insertedBreakList.size(); k++) {
                if (insertedBreakList.get(k).getEndTym().equals("")) {
                    masterBreakObject = insertedBreakList.get(k);
                    startTym = masterBreakObject.getStartTym();
                    txt_start_Tym.setText("Start Time - " + startTym);
                    flag_update = true;

                    promotion_btn_first.setBackgroundColor(getResources().getColor(R.color.green));
                    promotion_btn_first.setTextColor(getResources().getColor(R.color.white));
                    promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.round_btn_color_primary));
                    promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login));

                    break;
                }
            }

            recycl_break_managemnt.setAdapter(new ValueAdapter(context, insertedBreakList));
            recycl_break_managemnt.setLayoutManager(new LinearLayoutManager(context));


            if (flag_update) {
                if (flag) {
                    for (int k = 0; k < breakmanageList.size(); k++) {
                        if (breakmanageList.get(k).getBreakType().equalsIgnoreCase(masterBreakObject.getBreakType())) {
                            spin_break_Type.setSelection(k + 1);
                            spin_break_Type.setEnabled(false);
                            promotion_btn_first.setEnabled(false);

                            break;
                        }
                    }

                }
            }
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (clicked_flag) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                        (dialog, id1) -> {
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            BreakManagementActivity.this.finish();
                        }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                BreakManagementActivity.this.finish();
            }
        }


        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (clicked_flag) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                    (dialog, id) -> {
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        BreakManagementActivity.this.finish();
                    }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            BreakManagementActivity.this.finish();
        }
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.posm_btn_first) {
            if (spin_break_Type.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Break Type");
            } else if (!startTym.isEmpty()) {
                AlertandMessages.showToastMsg(context, "Already Take a Break");
            } else {
                alert = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage("Are you sure you want to Take a Break ?").setCancelable(false).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // hh:mm a will print hours in 12hrs clock, mins and AM/PM (e.g. 02:30 PM)
                        startTym = getTime();
                        txt_start_Tym.setText("Start Time - " + startTym);
                        promotion_btn_first.setBackgroundColor(getResources().getColor(R.color.green));

                        promotion_btn_first.setTextColor(getResources().getColor(R.color.white));
                        promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.round_btn_color_primary));
                        promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login));

                        masterBreakObject = new MasterBreak();
                        masterBreakObject.setLoginTym(loginTym);
                        masterBreakObject.setBreakType(breakType);
                        masterBreakObject.setBreakId(Integer.valueOf(breakId));
                        masterBreakObject.setStartTym(startTym);
                        masterBreakObject.setEndTym("");
                        masterBreakObject.setTotalDuration("");
                        db.open();
                        db.insertBreakManagement(username, visit_date, CounterId, masterBreakObject);
                        clicked_flag = false;
                        calcalate_list_data(true);
                    }
                }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss());

                alert.show();
            }

        } else if (view.getId() == R.id.posm_btn_second) {
            if (masterBreakObject != null && masterBreakObject.getStartTym().equals("")) {
                AlertandMessages.showToastMsg(context, "No Break.");
            } else {
                alert = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage("Are you sure you want to End The Break ?").setCancelable(false).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @SuppressLint("UseCompatLoadingForDrawables")
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        endTym = getTime();
                        promotion_btn_first.setBackgroundDrawable(getResources().getDrawable(R.drawable.round_btn_color_primary));
                        promotion_btn_first.setTextColor(getResources().getColor(R.color.grayfor_login));
                        promotion_btn_second.setBackgroundDrawable(getResources().getDrawable(R.drawable.round_btn_color_primary));
                        promotion_btn_second.setTextColor(getResources().getColor(R.color.grayfor_login));
                        db.open();
                        masterBreakObject.setEndTym(endTym);
                        masterBreakObject.setTotalDuration(calculateTotalDuration() + "");
                        masterBreakObject.setTransId(CommonFunctions.getUUID(context));
                        db.open();
                        db.update_break_management(CounterId, visit_date, username, masterBreakObject);
                        //download service
                        Intent intent = new Intent(context, Downloader.class);
                        intent.putExtra(CommonString.KEY_Break_Mangemennt, masterBreakObject);
                        Downloader.enqueueWork(context, intent);
                        AlertandMessages.showToastMsg(context, "Break End Successfully.");
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        BreakManagementActivity.this.finish();

                    }

                }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss());

                alert.show();
            }
        }

    }

    private void calculate_spin() {
        db.open();
        breakmanageList = db.getmasterBreak();
        break_managemntAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
        break_managemntAdapter.add("- Select Break Type -");

        for (int i = 0; i < breakmanageList.size(); i++) {
            break_managemntAdapter.add(breakmanageList.get(i).getBreakType());
        }

        spin_break_Type.setAdapter(break_managemntAdapter);
        break_managemntAdapter.setDropDownViewResource(R.layout.spinner_custom_item);
        spin_break_Type.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
        if (pos != 0) {
            clicked_flag = true;
            breakType = breakmanageList.get(pos - 1).getBreakType();
            breakId = breakmanageList.get(pos - 1).getBreakId().toString();
            if (breakType.equalsIgnoreCase("Lunch Break")) {
                if (!validatefor_lunch()) {
                    AlertandMessages.showToastMsg(context, "Only One Time Lunch Break Allowed");
                    spin_break_Type.setSelection(0);
                    breakType = "";
                    breakId = "0";
                }
            } else if (breakType.equalsIgnoreCase("Tea Break")) {
                if (validatefor_tea() == 2) {
                    AlertandMessages.showToastMsg(context, "Only Two Time Tea Break Allowed");
                    spin_break_Type.setSelection(0);
                    breakType = "";
                    breakId = "0";
                }
            }
        } else {
            breakType = "";
            breakId = "0";

        }
    }

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

    }

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

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


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

        @Override
        public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) {
            final MasterBreak current = data.get(position);

            holder.txt_breakType.setText(current.getBreakType());
            holder.txt_breakType.setId(position);

            holder.startTym.setText(current.getStartTym());
            holder.startTym.setId(position);

            holder.endTym.setText(current.getEndTym());
            holder.endTym.setId(position);

            holder.totalDuration.setText(current.getTotalDuration());
            holder.totalDuration.setId(position);

        }


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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView txt_breakType, startTym, endTym, totalDuration;

            public MyViewHolder(View itemView) {
                super(itemView);
                txt_breakType = (TextView) itemView.findViewById(R.id.txt_breakType);
                startTym = (TextView) itemView.findViewById(R.id.startTym);
                endTym = (TextView) itemView.findViewById(R.id.endTym);
                totalDuration = (TextView) itemView.findViewById(R.id.totalDuration);
            }
        }

    }

    private String getTime() {
        Calendar currnetDateTime = Calendar.getInstance();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
        return df.format(currnetDateTime.getTime());
    }

    private String calculateTotalDuration() {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
        int days = 0, hours = 0, min = 0;
        try {
            Date date1 = simpleDateFormat.parse(startTym);
            Date date2 = simpleDateFormat.parse(endTym);
            assert date2 != null;
            assert date1 != null;
            long difference = date2.getTime() - date1.getTime();
            days = (int) (difference / (1000 * 60 * 60 * 24));
            hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
            min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);
            hours = (hours < 0 ? -hours : hours);
            Log.i("======= Hours", " :: " + hours);
        } catch (ParseException e) {
            e.fillInStackTrace();
        }
        return hours + ":" + min;
    }

    private boolean validatefor_lunch() {
        String str = "Lunch";
        boolean flag = true;
        if (insertedBreakList.size() > 0) {
            for (int k = 0; k < insertedBreakList.size(); k++) {
                if (!insertedBreakList.get(k).getEndTym().equals("") && insertedBreakList.get(k).getBreakType().equalsIgnoreCase(str)) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    private int validatefor_tea() {
        String str = "Tea";
        int count = 0;
        if (insertedBreakList.size() > 0) {
            for (int k = 0; k < insertedBreakList.size(); k++) {
                if (!insertedBreakList.get(k).getEndTym().equals("") && insertedBreakList.get(k).getBreakType().equalsIgnoreCase(str)) {
                    count++;
                }
            }
        }
        return count;
    }
}
