package com.cpm.lorealbaautomation.dailyactivity;

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

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

import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
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.JourneyPlan;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

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

public class CounterProfileActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout lay_counter_ageing;
    private TextView edt_ageing, counter_type, countersetup_date;
    private EditText edt_width, edt_hight;
    private ImageView image1, image2, date, img_main;
    Toolbar toolbar;
    FloatingActionButton fab;
    String _pathforcheck, _path, counter_id, visit_date, username, user_type, dob, newvalueDate = "";
    ArrayList<JourneyPlan> storelist = new ArrayList<>();
    SharedPreferences preferences;
    SharedPreferences.Editor editor = null;
    private Lorealba_Database db;
    AlertDialog alert;
    Context context;
    JourneyPlan counterimg_object = new JourneyPlan();
    int mYear, mMonth, mDay;
    DatePickerDialog dpd;
    Calendar c;
    Dialog dialog1;
    WebView webview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter_profile);
        context = this;
        ((CounterProfileActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        db = new Lorealba_Database(context);
        db.open();
        getViewId();
        getSetData();
    }

    void getViewId() {
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        user_type = preferences.getString(CommonString.KEY_USER_TYPE, "");

        countersetup_date = (TextView) findViewById(R.id.storeProfile_dob);
        edt_ageing = (TextView) findViewById(R.id.edt_ageing);
        counter_type = (TextView) findViewById(R.id.counter_type);
        edt_width = (EditText) findViewById(R.id.edt_width);
        edt_hight = (EditText) findViewById(R.id.edt_hight);

        image1 = (ImageView) findViewById(R.id.image1);
        image2 = (ImageView) findViewById(R.id.image2);
        date = (ImageView) findViewById(R.id.date);
        lay_counter_ageing = (LinearLayout) findViewById(R.id.lay_counter_ageing);
        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);
        setTitle("Counter Profile - " + visit_date);
        fab = findViewById(R.id.fab);
        fab.setOnClickListener(this);
        image1.setOnClickListener(this);
        image2.setOnClickListener(this);
        date.setOnClickListener(this);
        image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs));
    }


    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("MakeMachine", "resultCode: " + resultCode);
        switch (resultCode) {

            case 0:
                Log.i("MakeMachine", "User cancelled");
                break;

            case -1:
                if (_pathforcheck != null && !_pathforcheck.isEmpty()) {
                    if (new File(CommonString.getImagesFolder(context) + _pathforcheck).exists()) {
                        convertBitmap(CommonString.getImagesFolder(context) + _pathforcheck);
                        if (_pathforcheck.contains("_cp_img_one_")) {
                            image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                            counterimg_object.setProfileImage1(_pathforcheck);

                        } else if (_pathforcheck.contains("_cp_img_two_")) {
                            image2.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                            counterimg_object.setProfileImage2(_pathforcheck);
                        }

                        _pathforcheck = "";
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean validateimg_str() {
        boolean status = true;
        if (counterimg_object.getProfileImage1() == null && counterimg_object.getProfileImage2() == null) {
            AlertandMessages.showToastMsg(context, "Please Click Any Profile Imges");
            status = false;
        } else if (edt_hight.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Fill Counter Dimensions Height In (Feet)");
            status = false;
        } else if (edt_width.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Fill Counter Dimensions Width In (Feet)");
            status = false;
        } else if (countersetup_date.getText().toString().isEmpty()) {
            AlertandMessages.showToastMsg(context, "Please Select Counter Set Up Date");
            status = false;

        }

        return status;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.image1) {
            _pathforcheck = counter_id + "_cp_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            CommonFunctions.startAnncaCameraActivity(this, _path, null,
                    false, CommonString.CAMERA_FACE_REAR);
        } else if (view.getId() == R.id.image2) {
            _pathforcheck = counter_id + "_cp_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
            _path = CommonString.getImagesFolder(context) + _pathforcheck;
            CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
        } else if (view.getId() == R.id.date) {
            c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            // Launch Date Picker Dialog
            //mm dd yy
            dpd = new DatePickerDialog(this, (_view, year, monthOfYear, dayOfMonth) -> {
                dob = (monthOfYear + 1) + "/" + dayOfMonth + "/" + year;
                lay_counter_ageing.setVisibility(View.VISIBLE);
                Date counterAgeing_date = null, current_date = null;
                @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
                if (!dob.isEmpty()) {
                    String str_monthofYears = "", str_dayofmonth = "";
                    int monthofyears = monthOfYear + 1;
                    if (monthofyears < 10) {
                        str_monthofYears = "0" + monthofyears;
                    } else {
                        str_monthofYears = "" + monthofyears;
                    }

                    if (dayOfMonth < 10) {
                        str_dayofmonth = "0" + dayOfMonth;
                    } else {
                        str_dayofmonth = "" + dayOfMonth;
                    }

                    newvalueDate = str_monthofYears + "/" + str_dayofmonth + "/" + year;
                    countersetup_date.setText(newvalueDate);
                }
                try {
                    counterAgeing_date = dateFormat.parse(newvalueDate);
                    current_date = dateFormat.parse(visit_date);
                    printDifference(current_date, counterAgeing_date);
                } catch (ParseException e) {
                    e.fillInStackTrace();
                }
            }, mYear, mMonth, mDay);
            dpd.getDatePicker().setMaxDate(System.currentTimeMillis());
            dpd.show();
        } else if (view.getId() == R.id.fab) {
            if (validateimg_str()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.title_activity_save_data).setCancelable(false)
                        .setPositiveButton(android.R.string.yes, (dialog, id1) -> {
                            alert.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                            db.open();
                            counterimg_object.setSetupDate(newvalueDate);
                            double counter_width = 0.0, counter_lenth = 0.0;
                            String str_width = edt_width.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "");
                            String str_lenth = edt_hight.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", "");
                            if (!str_width.isEmpty()) {
                                counter_width = Double.parseDouble(str_width);
                            }

                            if (!str_lenth.isEmpty()) {
                                counter_lenth = Double.parseDouble(str_lenth);
                            }

                            counterimg_object.setCounterwidth(counter_width);
                            counterimg_object.setCounterlength(counter_lenth);
                            String status = CommonString.KEY_N;
                            String uuid_Id = CommonFunctions.getUUID(context);
                            db.open();
                            db.insertCounterProfiledata(counter_id, username, user_type, visit_date, counterimg_object, status, uuid_Id);

                            //download service
                            Intent intent = new Intent(context, Downloader.class);
                            intent.putExtra(CommonString.KEY_CounterProfile, counterimg_object);
                            Downloader.enqueueWork(CounterProfileActivity.this, intent);

                            AlertandMessages.showToastMsg(context, "Data saved successfully.");
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            CounterProfileActivity.this.finish();

                        }).setNegativeButton(android.R.string.cancel, (dialog, id12) -> dialog.cancel());

                alert = builder.create();
                alert.show();
            }

        }


    }

    @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) {
            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);
                        CounterProfileActivity.this.finish();
                    }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel());
            AlertDialog alert = builder.create();
            alert.show();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        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);
                    CounterProfileActivity.this.finish();
                }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());
        AlertDialog alert = builder.create();
        alert.show();
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void popup(final String window_image) {
        dialog1 = new Dialog(CounterProfileActivity.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);
        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) {
            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);
        }

    }

    @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
    void getSetData() {
        db.open();
        storelist = db.getStoreData(visit_date, null, counter_id);
        counterimg_object = db.getCounterProfileData(null, visit_date, counter_id, true);
        if (counterimg_object.getUserId() != null && !counterimg_object.getUserId().isEmpty()) {
            edt_hight.setText("" + counterimg_object.getCounterlength());
            edt_width.setText("" + counterimg_object.getCounterwidth());
            if (counterimg_object.getProfileImage1() != null) {
                image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                fab.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.edit));
                lay_counter_ageing.setVisibility(View.VISIBLE);
            }

            edt_ageing.setText(counterimg_object.getStoreName() + " Days");
            counterimg_object.setStoreName(counterimg_object.getStoreName());
            countersetup_date.setText(counterimg_object.getSetupDate());
            newvalueDate = counterimg_object.getSetupDate();
            if (counterimg_object.getProfileImage2() != null) {
                image2.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
            }

            if (!storelist.isEmpty()) {
                counter_type.setText(storelist.get(0).getStoreTypeName());
            }

        } else {
            if (!storelist.isEmpty()) {
                edt_hight.setText("" + storelist.get(0).getCounterlength());
                edt_width.setText("" + storelist.get(0).getCounterwidth());
                if (storelist.get(0).getStoreTypeName().isEmpty()) {
                } else {
                    counter_type.setText(storelist.get(0).getStoreTypeName());
                }
                if (storelist.get(0).getProfileImage1().isEmpty()) {
                    image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs));
                } else {
                    counterimg_object.setProfileImage1(storelist.get(0).getProfileImage1());
                    image1.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                }

                if (storelist.get(0).getProfileImage2().isEmpty()) {
                    image2.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bs));
                } else {
                    counterimg_object.setProfileImage2(storelist.get(0).getProfileImage2());
                    image2.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                }


                //////////parshing date and counter agaiging.......
                if (!storelist.get(0).getSetupDate().isEmpty()) {
                    counterimg_object.setSetupDate(storelist.get(0).getSetupDate());
                    countersetup_date.setText(storelist.get(0).getSetupDate());
                    Date counterAgeing_date = null, current_date = null;
                    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
                    try {
                        counterAgeing_date = dateFormat.parse(storelist.get(0).getSetupDate());
                        current_date = dateFormat.parse(visit_date);
                        printDifference(current_date, counterAgeing_date);
                        lay_counter_ageing.setVisibility(View.VISIBLE);
                        newvalueDate = storelist.get(0).getSetupDate();
                    } catch (ParseException e) {
                        e.fillInStackTrace();
                    }
                } else {
                    edt_ageing.setText("0 Days");
                    counterimg_object.setSetupDate("");
                    countersetup_date.setText("");
                }
            }
        }
    }

    public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
        try {
            return TimeUnit.DAYS.convert(Objects.requireNonNull(format.parse(newDate)).getTime() - Objects.requireNonNull(format.parse(oldDate)).getTime(), TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.fillInStackTrace();
            return 0;
        }
    }

    @SuppressLint("SetTextI18n")
    public void printDifference(Date startDate, Date endDate) {
        try {
            long different = startDate.getTime() - endDate.getTime();
            long secondsInMilli = 1000;
            long minutesInMilli = secondsInMilli * 60;
            long hoursInMilli = minutesInMilli * 60;
            long daysInMilli = hoursInMilli * 24;
            long elapsedDays = different / daysInMilli;
            different = different % daysInMilli;
            long elapsedHours = different / hoursInMilli;
            different = different % hoursInMilli;
            long elapsedMinutes = different / minutesInMilli;
            different = different % minutesInMilli;
            long elapsedSeconds = different / secondsInMilli;
            System.out.printf("%d days, %d hours, %d minutes, %d seconds%n", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
            edt_ageing.setText((int) elapsedDays + " Days ");
            counterimg_object.setStoreName(String.valueOf(elapsedDays));

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