package com.kaviz.heal.Activities;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.SparseArray;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.kaviz.heal.API.ApiRequestData;
import com.kaviz.heal.API.RetroServer;
import com.kaviz.heal.Model.Pharmacy;
import com.kaviz.heal.Model.ResponseModelThree;
import com.kaviz.heal.R;
import com.kaviz.heal.databinding.ActivityPrescriptionScanBinding;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PrescriptionScanActivity extends AppCompatActivity {

    private ActivityPrescriptionScanBinding binding;

    private static final int REQUEST_CAMERA_CODE = 100;
    private Bitmap bitmap;
    private static final int REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPrescriptionScanBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        if (getSupportActionBar() != null) {

            getSupportActionBar().setTitle(getResources().getString(R.string.prescription_scan));

        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_CODE);

        }

        binding.scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                binding.dataText.setText("");
                CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).start(PrescriptionScanActivity.this);

            }
        });

        binding.sendPrescriptionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                sendLocationWithData();

            }
        });

    }

    private void sendLocationWithData() {

        binding.progressBar.setVisibility(View.VISIBLE);

        final String location = "6.9154908,79.9726544";
        final String medicines = binding.dataText.getText().toString().toLowerCase();

        JSONObject jsonObjectMain = new JSONObject();

        try {

            jsonObjectMain.put("user_location", location);
            jsonObjectMain.put("medicine_list", medicines);

        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonObjectMain.toString());

        System.out.println(jsonObject.toString());

        ApiRequestData apiRequestData = RetroServer.connectRetrofit().create(ApiRequestData.class);
        Call<ResponseModelThree>getPharmacies = apiRequestData.getPharmacies(jsonObject);
        getPharmacies.enqueue(new Callback<ResponseModelThree>() {
            @Override
            public void onResponse(@NonNull Call<ResponseModelThree> call, @NonNull Response<ResponseModelThree> response) {

                if (response.isSuccessful()) {

                    if (response.body().getStatus().equals("success")) {

                        ArrayList<Pharmacy> pharmacyList = (ArrayList<Pharmacy>) response.body().getPharmacy_recommendation();
                        System.out.println(pharmacyList.get(0).getName());

                        if (!pharmacyList.isEmpty()) {

                            Intent intent = new Intent(PrescriptionScanActivity.this, ShowPharmaciesActivity.class);
                            intent.putExtra("PharmacyList", pharmacyList);
                            intent.putExtra("Medicines", medicines);
                            startActivity(intent);
                            
                        } else {

                            Toast.makeText(PrescriptionScanActivity.this, "No pharmacy could be found!", Toast.LENGTH_SHORT).show();
                            
                        }

                        binding.progressBar.setVisibility(View.GONE);

                    }

                }

            }

            @Override
            public void onFailure(@NonNull Call<ResponseModelThree> call, @NonNull Throwable t) {

                Toast.makeText(PrescriptionScanActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                binding.progressBar.setVisibility(View.GONE);

            }
        });

        binding.progressBar.setVisibility(View.GONE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {

                Uri uri = result.getUri();
                try {

                    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                    getTextFromImage(bitmap);

                } catch (Exception e) {

                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();

                }

            }

        }

    }

    private void getTextFromImage(Bitmap bitmap) {

        TextRecognizer recognizer = new TextRecognizer.Builder(this).build();

        if (!recognizer.isOperational()) {

            Toast.makeText(this, "Something Wrong!", Toast.LENGTH_SHORT).show();

        } else {

            Frame frame = new Frame.Builder().setBitmap(bitmap).build();
            SparseArray<TextBlock> textBlockSparseArray = recognizer.detect(frame);
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < textBlockSparseArray.size(); i++) {

                TextBlock textBlock = textBlockSparseArray.valueAt(i);
                stringBuilder.append(textBlock.getValue());
                //stringBuilder.append("\n");

            }

            binding.dataText.setText(stringBuilder.toString());
            binding.scanButton.setText(R.string.retake);
            binding.sendPrescriptionButton.setVisibility(View.VISIBLE);

        }

    }

}