package com.cygnusa.hyperm;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.cygnusa.hyperm.cropview.CropImageView;
import com.cygnusa.hyperm.cropview.callback.CropCallback;
import com.cygnusa.hyperm.cropview.callback.LoadCallback;
import com.cygnusa.hyperm.util.TransparentProgressDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class CropActivity extends AppCompatActivity {

    public static Uri mSourceUri;
    CropImageView mCropView;
    TransparentProgressDialog progressDialog;
    private Bitmap.CompressFormat mCompressFormat = Bitmap.CompressFormat.JPEG;
    String IMAGE_PATH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.crop_image_activity);
        setupWindowAnimations();

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        mCropView = findViewById(R.id.cropImageView);

        findViewById(R.id.buttonRotateLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
            }
        });

        findViewById(R.id.buttonRotateRight).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
            }
        });

        findViewById(R.id.buttonPickImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent result = new Intent();
                setResult(Activity.RESULT_CANCELED, result);
                finish();
            }
        });

        findViewById(R.id.buttonDone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cropImage();
            }
        });

        File f = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null), ".HYPERM");
        if (!f.exists()) {
            f.mkdirs();
        }

        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null) + "/" + ".HYPERM", "Profile");
        if (!f1.exists()) {
            f1.mkdirs();
        }

        mCropView.post(new Runnable() {
            @Override
            public void run() {
                loadImage();
            }
        });
    }

    @Override
    public void onBackPressed() {
        Intent result = new Intent();
        setResult(Activity.RESULT_CANCELED, result);
        finish();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            Intent result = new Intent();
            setResult(Activity.RESULT_CANCELED, result);
            finish();
            overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadImage() {
        mCropView.load(mSourceUri).execute(new LoadCallback() {
            @Override
            public void onSuccess() {
                mCropView.setCropMode(CropImageView.CropMode.SQUARE);
            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(CropActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void cropImage() {
        showProgress();
        mCropView.crop(mSourceUri).execute(new CropCallback() {
            @Override
            public void onSuccess(Bitmap cropped) {
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                String imageFileName = timeStamp + ".jpg";
                File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null) + "/" + ".HYPERM/Profile", imageFileName);
                IMAGE_PATH = f1.getAbsolutePath();
                try {
                    FileOutputStream out = new FileOutputStream(f1);
                    cropped.compress(Bitmap.CompressFormat.JPEG, 60, out);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissProgress();
                Intent result = new Intent();
                result.setData(Uri.fromFile(f1));
                result.putExtra("IMAGE_PATH", IMAGE_PATH);
                setResult(Activity.RESULT_OK, result);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgress();
            }
        });
    }

    public void showProgress() {
        progressDialog = new TransparentProgressDialog(CropActivity.this);
        progressDialog.show();
    }

    public void dismissProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}
