package com.cpm.lorealbaMabeline.dailyactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;

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

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.constant.FileUtils;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Objects;

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

public class SkinGeniusScreenshotActivity extends AppCompatActivity implements View.OnClickListener {
    String CounterId, visit_date, username, skingenius_uploadTym = "";
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor = null;
    Lorealba_Database db;
    Context context;

    ImageView img_cam, img_clicked;
    FloatingActionButton save_skin_genius;
    TextView skingenius_capturedTym;
    String img_str = "";
    private final boolean clicked_flag = false;
    int FILE_PICKER_CODE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_skin_genius_screenshot);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        iduserinterface();
        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);
        }

        setTitle("Skin Genius Screenshot - " + username);

    }

    @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, "");
        skingenius_uploadTym = preferences.getString(CommonString.KEY_SKIN_GENIUS_UPLOADTYM, "");

        img_cam = (ImageView) findViewById(R.id.img_selfie);
        img_clicked = (ImageView) findViewById(R.id.img_cam_selfie);
        skingenius_capturedTym = (TextView) findViewById(R.id.skingenius_capturedTym);
        save_skin_genius = (FloatingActionButton) findViewById(R.id.save_skin_genius);

        if (skingenius_uploadTym != null && !skingenius_uploadTym.isEmpty()) {
            skingenius_capturedTym.setText("Last Skin Genius Uploaded Time : " + skingenius_uploadTym);
        }

        img_cam.setOnClickListener(this);
        img_clicked.setOnClickListener(this);
        save_skin_genius.setOnClickListener(this);
    }


    @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);
                        SkinGeniusScreenshotActivity.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);
            SkinGeniusScreenshotActivity.this.finish();
        }
    }


    @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);
                            SkinGeniusScreenshotActivity.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);
                SkinGeniusScreenshotActivity.this.finish();
            }
        }
        return super.onOptionsItemSelected(item);
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.img_cam_selfie) {
            browseDocuments();
        } else if (v.getId() == R.id.save_skin_genius) {
            if (img_str != null && !img_str.isEmpty()) {
                AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getString(R.string.alertsaveData))
                        .setCancelable(false).setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                            db.open();
                            long l = db.insertSkinGeniusdata(username, visit_date, CounterId, CommonFunctions.getUUID(context), img_str, CommonFunctions.getCurrentTime_only());
                            if (l > 0) {
                                editor = preferences.edit();
                                editor.putString(CommonString.KEY_SKIN_GENIUS_UPLOADTYM, visit_date + " : " + CommonFunctions.getCurrentTime_only());
                                editor.commit();
                                AlertandMessages.showToastMsg(context, "Data saved successfully.");
                                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                                SkinGeniusScreenshotActivity.this.finish();
                                CommonFunctions.call_upload(context);
                            } else {
                                AlertandMessages.showToastMsg(context, "Data not inserted");
                            }
                        }).setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss());

                alert.show();

            } else {
                AlertandMessages.showToastMsg(context, "Please Pickup Skin Genius Screenshot");
            }

        }

    }

    public boolean checkNetIsAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }


    private void browseDocuments() {
        String[] mimeTypes =
                {"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                        "image/jpeg",
                        "image/jpg", "image/png"};

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        startActivityForResult(Intent.createChooser(intent, "Choose Skin Genius Screenshot"), FILE_PICKER_CODE);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == FILE_PICKER_CODE) {
                Uri uri = data.getData();
                assert uri != null;
                String uriString = uri.toString();
                String displayName = null;

                if (uriString.startsWith("content://")) {
                    try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                        if (cursor != null && cursor.moveToFirst()) {
                            displayName = CounterId + username.replace(".", "") + "-SkinGenius-" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
                        }
                    }
                } else if (uriString.startsWith("file://")) {
                    displayName = CounterId + username.replace(".", "") + "-SkinGenius-" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
                }
                try {
                    File sourceLocation = null;
                    sourceLocation = FileUtils.getFile(context, uri);
                    File targetLocation = new File(CommonString.getImagesFolder(context) + displayName);
                    if (sourceLocation != null) {
                        InputStream in = null;
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                            in = Files.newInputStream(sourceLocation.toPath());
                        } else {
                            in = new FileInputStream(sourceLocation);
                        }
                        OutputStream out = null;
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                            out = Files.newOutputStream(targetLocation.toPath());
                        } else out = new FileOutputStream(targetLocation);
                        // Copy the bits from instream to outstream
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                        in.close();
                        out.close();
                        img_str = displayName;
                        if (new File(CommonString.getImagesFolder(context) + img_str).exists()) {
                            try {
                                Bitmap bmp = convertBitmap(CommonString.getImagesFolder(context) + img_str);
                                img_cam.setImageBitmap(bmp);
                            } catch (OutOfMemoryError ex) {
                                CommonFunctions.setScaledImage(img_cam, CommonString.getImagesFolder(context) + img_str);
                            }
                            img_clicked.setVisibility(View.GONE);
                            img_cam.setVisibility(View.VISIBLE);
                        }
                    } else {
                        AlertandMessages.showToastMsg(context, "Unable to retrieve the path. Please try again");
                    }
                } catch (IOException e) {
                    e.fillInStackTrace();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
