package com.cpm.lorealbaautomation.dailyactivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;

import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

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

import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.gms.location.LocationServices;
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.util.List;
import java.util.Objects;

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

public class CounterImageActivity extends AppCompatActivity implements
        View.OnClickListener {
    ImageView presetup_img_one, presetup_img_two, post_setup_img_one, post_setup_img_two,/*.......*/
            counter_img_one, counter_img_two;
    String _pathforcheck, _path, counter_id, visit_date, username, user_type;
    FloatingActionButton btn_save_selfie;
    private static final int REQUEST_LOCATION = 1;
    JourneyPlan counterimg_object = new JourneyPlan();
    LinearLayout layout_for_me_counterimg, layout_for_ba_counterimg;
    SharedPreferences preferences;
    private Lorealba_Database db;
    double lat = 0.0, lon = 0.0;
    boolean update_flag = false, click_flag = true;
    AlertDialog alert;
    Context context;
    private FusedLocationProviderClient fusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter_image);
        context = this;
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        getLastLocation();
        db = new Lorealba_Database(context);
        db.open();
        validateuidata();
        if (!db.isBaProfileFilled(counter_id, username, user_type) && db.getSaveServerData(null, username).isEmpty()) {
            // Only show if BOTH are false
            showAlertProfile(context);
        }
    }

    private void getLastLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Request location permissions
            return;
        }
        try {
            fusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, location -> {
                        if (location != null) {
                            lat = location.getLatitude();
                            lon = location.getLongitude();
                            //test("Location", "Lat: " + lat + ", Lng: " + lon);
                        }
                    });
        } catch (Exception e) {
            e.fillInStackTrace(); //test("Location", "Lat: " + lat + ", Lng: " + lon);}
        }
    }

    @SuppressLint("RestrictedApi")
    private void validateuidata() {
        preferences = PrefHelper.getPrefs(context);
        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, "");
        presetup_img_one = (ImageView) findViewById(R.id.presetup_img_one);
        presetup_img_two = (ImageView) findViewById(R.id.presetup_img_two);
        post_setup_img_one = (ImageView) findViewById(R.id.post_setup_img_one);
        post_setup_img_two = (ImageView) findViewById(R.id.post_setup_img_two);
        btn_save_selfie = (FloatingActionButton) findViewById(R.id.btn_save_selfie);
        ////new changes
        layout_for_me_counterimg = (LinearLayout) findViewById(R.id.layout_for_me_counterimg);
        layout_for_ba_counterimg = (LinearLayout) findViewById(R.id.layout_for_ba_counterimg);
        counter_img_one = (ImageView) findViewById(R.id.counter_img_one);
        counter_img_two = (ImageView) findViewById(R.id.counter_img_two);

        presetup_img_one.setOnClickListener(this);
        presetup_img_two.setOnClickListener(this);
        post_setup_img_one.setOnClickListener(this);
        post_setup_img_two.setOnClickListener(this);
        btn_save_selfie.setOnClickListener(this);
        counter_img_one.setOnClickListener(this);
        counter_img_two.setOnClickListener(this);
        setTitle("Counter Image - " + visit_date);
        db.open();
        counterimg_object = db.getinserted_counter_images(counter_id, visit_date);
        if (!user_type.isEmpty() && user_type.equalsIgnoreCase("BA") || !user_type.isEmpty() && user_type.equalsIgnoreCase("TBA")) {
            if (counterimg_object != null && !counterimg_object.getCounter_img_onefor_ba().isEmpty() || !counterimg_object.getCounter_img_two_for_ba().isEmpty()) {
                btn_save_selfie.setVisibility(View.GONE);
                update_flag = true;
                validate_ui();
            }
            layout_for_ba_counterimg.setVisibility(View.VISIBLE);
            layout_for_me_counterimg.setVisibility(View.GONE);
        } else {
            layout_for_ba_counterimg.setVisibility(View.GONE);
            layout_for_me_counterimg.setVisibility(View.VISIBLE);
            if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) {
                update_flag = true;
                validate_ui();
            }
        }
    }


    @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 (click_flag) {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                CounterImageActivity.this.finish();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                        (dialog, id12) -> {
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            CounterImageActivity.this.finish();
                        }).setNegativeButton("Cancel", (dialog, id1) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        if (click_flag) {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            CounterImageActivity.this.finish();
        } else {
            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);
                        CounterImageActivity.this.finish();
                    }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());
            AlertDialog alert = builder.create();
            alert.show();
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.counter_img_one) {
            if (!update_flag) {
                click_flag = false;
                _pathforcheck = counter_id + "_counter_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + _pathforcheck;
                CommonFunctions.startAnncaCameraActivity(this, _path, null,
                        false, CommonString.CAMERA_FACE_REAR);
            } else {
                show_image_preview(context, counterimg_object.getCounter_img_onefor_ba());
            }
        } else if (view.getId() == R.id.counter_img_two) {
            if (!update_flag) {
                click_flag = false;
                _pathforcheck = counter_id + "_counter_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + _pathforcheck;
                CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
            } else {
                if (!counterimg_object.getCounter_img_two_for_ba().isEmpty()) {
                    show_image_preview(context, counterimg_object.getCounter_img_two_for_ba());
                }
            }

        } else if (view.getId() == R.id.presetup_img_one) {
            if (update_flag) {
                if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) {
                    show_image_preview(context, counterimg_object.getPresetup_img_one_str());
                }
            } else {
                if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) {
                    show_image_preview(context, counterimg_object.getPresetup_img_one_str());
                } else {
                    click_flag = false;
                    _pathforcheck = counter_id + "_presetup_counter_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
                }
            }

        } else if (view.getId() == R.id.presetup_img_two) {
            if (update_flag) {
                if (counterimg_object != null && !counterimg_object.getPresetup_img_two_str().isEmpty()) {
                    show_image_preview(context, counterimg_object.getPresetup_img_two_str());
                }
            } else {
                if (counterimg_object != null && !counterimg_object.getPresetup_img_two_str().isEmpty()) {
                    show_image_preview(context, counterimg_object.getPresetup_img_two_str());
                } else {
                    click_flag = false;
                    _pathforcheck = counter_id + "_presetup_counter_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
                }
            }

        } else if (view.getId() == R.id.post_setup_img_one) {
            if (update_flag) {
                if (counterimg_object != null && !counterimg_object.getPostsetup_img_one_str().isEmpty()) {
                    show_image_preview(context, counterimg_object.getPostsetup_img_one_str());
                } else {
                    click_flag = false;
                    _pathforcheck = counter_id + "_postsetup_counter_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
                }

            } else if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) {
                click_flag = false;
                _pathforcheck = counter_id + "_postsetup_counter_img_one_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + _pathforcheck;
                CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
            }

        } else if (view.getId() == R.id.post_setup_img_two) {
            if (update_flag) {
                if (counterimg_object != null && !counterimg_object.getPostsetup_img_two_str().isEmpty()) {
                    show_image_preview(context, counterimg_object.getPostsetup_img_two_str());
                } else {
                    click_flag = false;
                    _pathforcheck = counter_id + "_possetup_counter_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg";
                    _path = CommonString.getImagesFolder(context) + _pathforcheck;
                    CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
                }
            } else if (counterimg_object != null && !counterimg_object.getPresetup_img_one_str().isEmpty()) {
                click_flag = false;
                _pathforcheck = counter_id + "_possetup_counter_img_two_" + visit_date.replace("/", "") + "_" + getCurrentTime_only().replace(":", "") + ".jpg";
                _path = CommonString.getImagesFolder(context) + _pathforcheck;
                CommonFunctions.startAnncaCameraActivity(this, _path, null, false, CommonString.CAMERA_FACE_REAR);
            }

        } else if (view.getId() == R.id.btn_save_selfie) {
            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();
                            if (!user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_BA)
                                    || !user_type.isEmpty() && user_type.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) {
                                counterimg_object.setTransId(CommonFunctions.getUUID(context));
                                db.insertcounteruserdata(counter_id, username, visit_date, counterimg_object, user_type);
                                //download service
                                Intent intent = new Intent(context, Downloader.class);
                                intent.putExtra(CommonString.KEY_BA_Counter_Image, counterimg_object);
                                Downloader.enqueueWork(context, intent);
                            } else {
                                db.open();
                                if (update_flag) {
                                    counterimg_object.setTransId(CommonFunctions.getUUID(context));
                                    db.update_CounterImage(counter_id, username, visit_date, counterimg_object);
                                } else {
                                    counterimg_object.setTransId(CommonFunctions.getUUID(context));
                                    db.insertcounteruserdata(counter_id, username, visit_date, counterimg_object, user_type);
                                }
                                Intent intent = new Intent(context, Downloader.class);
                                intent.putExtra(CommonString.KEY_Me_Counter_Image, counterimg_object);
                                Downloader.enqueueWork(context, intent);
                            }

                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            AlertandMessages.showToastMsg(context, "Data saved successfully.");
                            CounterImageActivity.this.finish();
                        }).setNegativeButton(android.R.string.cancel, (dialog, id12) -> dialog.cancel());

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

        }
    }

    @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);
                        try {
                            if (_pathforcheck.contains("_presetup_counter_img_one_")) {
                                presetup_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                                counterimg_object.setPresetup_img_one_str(_pathforcheck);
                            } else if (_pathforcheck.contains("_presetup_counter_img_two_")) {
                                presetup_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                                counterimg_object.setPresetup_img_two_str(_pathforcheck);
                            } else if (_pathforcheck.contains("_postsetup_counter_img_one_")) {
                                post_setup_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                                counterimg_object.setPostsetup_img_one_str(_pathforcheck);

                            } else if (_pathforcheck.contains("_possetup_counter_img_two_")) {
                                post_setup_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                                counterimg_object.setPostsetup_img_two_str(_pathforcheck);
                            } else if (_pathforcheck.contains("_counter_img_one_")) {
                                counter_img_one.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                                counterimg_object.setCounter_img_onefor_ba(_pathforcheck);
                            } else if (_pathforcheck.contains("_counter_img_two_")) {
                                counter_img_two.setImageDrawable(getResources().getDrawable(R.mipmap.camera_bsd));
                                counterimg_object.setCounter_img_two_for_ba(_pathforcheck);
                            }

                        } catch (OutOfMemoryError ex) {
                            ex.fillInStackTrace();
                        }

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

    @SuppressLint("UseCompatLoadingForDrawables")
    private void validate_ui() {
        if (!counterimg_object.getPresetup_img_one_str().isEmpty()) {
            presetup_img_one.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.camera_bsd));
        }
        if (!counterimg_object.getPresetup_img_two_str().isEmpty()) {
            presetup_img_two.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.camera_bsd));
        }
        if (!counterimg_object.getPostsetup_img_one_str().isEmpty()) {
            post_setup_img_one.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.camera_bsd));
        }
        if (!counterimg_object.getPostsetup_img_two_str().isEmpty()) {
            post_setup_img_two.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.camera_bsd));
        }

        if (!counterimg_object.getCounter_img_onefor_ba().isEmpty()) {
            counter_img_one.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.camera_bsd));
        }

        if (!counterimg_object.getCounter_img_two_for_ba().isEmpty()) {
            counter_img_two.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.camera_bsd));
        }

    }

    private boolean validateimg_str() {
        boolean status = true;
        if (user_type != null && user_type.equalsIgnoreCase("BA") || user_type != null && user_type.equalsIgnoreCase("TBA")) {
            if (!counterimg_object.getCounter_img_onefor_ba().isEmpty()) {
                status = true;
            } else {
                AlertandMessages.showToastMsg(context, "Please click Counter Images");
                status = false;
            }
        } else {
            if (!update_flag) {
                if (counterimg_object.getPresetup_img_one_str().isEmpty()) {
                    AlertandMessages.showToastMsg(context, "Please click Pre Set-Up Counter Images");
                    status = false;
                }
            } else if (counterimg_object.getPostsetup_img_one_str().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please click Post Set-Up Counter Images");
                status = false;
            }
        }

        return status;

    }


    public void showAlertProfile(final Context context) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        final Dialog dialogcounter = new Dialog(context);
        Objects.requireNonNull(dialogcounter.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialogcounter.setContentView(R.layout.dialog_alert_profile);
        Window window = dialogcounter.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CENTER;
        window.setAttributes(wlp);
        dialogcounter.setCancelable(false);
        dialogcounter.setCanceledOnTouchOutside(false);
        RelativeLayout rl_dialog = dialogcounter.findViewById(R.id.rl_dialog);
        rl_dialog.setOnClickListener(view -> {
            startActivity(new Intent(context, BAProfileActivity.class));
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            dialogcounter.dismiss();
        });

        dialogcounter.show();

    }

    @Override
    protected void onResume() {
        super.onResume();
        db.open();
        checkgpsEnableDevice();
        /*if (!db.isBaProfileFilled(counter_id, username, user_type)) {
            showAlertProfile(context);
        } else if (db.getSaveServerData(null, username).isEmpty()) {
            showAlertProfile(context);
        }*/
    }

    private void checkgpsEnableDevice() {
        if (!hasGPSDevice(context)) {
            Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show();
        }

        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) {
            enableLocationSettings();
        } else {
            if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                hasGPSDevice(context);
            }
        }
    }

    private void enableLocationSettings() {
        @SuppressLint("VisibleForTests") LocationRequest locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) // new Priority constant
                .setInterval(30 * 1000)
                .setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest)
                .setAlwaysShow(true); // show dialog if GPS is off

        SettingsClient settingsClient = LocationServices.getSettingsClient(this);

        settingsClient.checkLocationSettings(builder.build())
                .addOnSuccessListener(locationSettingsResponse -> {
                    // All location settings are satisfied. You can request location updates here.
                }).addOnFailureListener(e -> {
                    if (e instanceof ResolvableApiException) {
                        try {
                            ResolvableApiException resolvable = (ResolvableApiException) e;
                            resolvable.startResolutionForResult((Activity) context, REQUEST_LOCATION);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error.
                            sendEx.fillInStackTrace();
                        }
                    }
                });
    }

    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null)
            return false;
        final List<String> providers = mgr.getAllProviders();
        return providers.contains(LocationManager.GPS_PROVIDER);
    }
}
