package com.example.eketha;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;

import com.example.eketha.ml.Dmodel;

public class Diseases extends AppCompatActivity {

    private Button camera, gallery;
    private ImageView imageView;
    private TextView result;
    private int imageSize = 250;
    private TextView solutionDiseases;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diseases);

        camera = findViewById(R.id.btnTakePicture);
        gallery = findViewById(R.id.btnLaunchGallery);

        result = findViewById(R.id.result1);
        imageView = findViewById(R.id.imageView1);
        solutionDiseases=findViewById(R.id.solutionDeseases);

        camera.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View view) {
                if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, 3);
                } else {
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                }
            }
        });
        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(cameraIntent, 1);
            }
        });
    }

    public void classifyImage1(Bitmap image){
        try {
            //Model model = Model.newInstance(getApplicationContext());

            // Creates inputs for reference.
            TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 250, 250, 3}, DataType.FLOAT32);
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * imageSize * imageSize * 3);
            byteBuffer.order(ByteOrder.nativeOrder());

            int[] intValues = new int[imageSize * imageSize];
            image.getPixels(intValues, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
            int pixel = 0;
            //iterate over each pixel and extract R, G, and B values. Add those values individually to the byte buffer.
            for(int i = 0; i < imageSize; i ++){
                for(int j = 0; j < imageSize; j++){
                    int val = intValues[pixel++]; // RGB
                    byteBuffer.putFloat(((val >> 16) & 0xFF) * (1.f / 1));
                    byteBuffer.putFloat(((val >> 8) & 0xFF) * (1.f / 1));
                    byteBuffer.putFloat((val & 0xFF) * (1.f / 1));
                }
            }

            inputFeature0.loadBuffer(byteBuffer);

            // Runs model inference and gets result.
            Dmodel dModel = Dmodel.newInstance(getApplicationContext());
            Dmodel.Outputs outputs = dModel.process(inputFeature0);
            TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();

            float[] confidences = outputFeature0.getFloatArray();
            // find the index of the class with the biggest confidence.
            int maxPos = 0;
            float maxConfidence = 0;
            for (int i = 0; i < confidences.length; i++) {
                if (confidences[i] > maxConfidence) {
                    maxConfidence = confidences[i];
                    maxPos = i;
                }
            }
            String[] classes = {"Bacterialblight", "Blast", "Brownspot", "Tungro"};
            System.out.println("Log diseases"+classes[maxPos]);
            result.setText(classes[maxPos]);

            if(classes[maxPos].equals("Bacterialblight")){
                solutionDiseases.setText("Bacterial blight is caused by the bacterium Pseudomonas syringae pv. syringae (Pss), which survives in diseased stem tissue (cankers), plant debris, and soil. Pss can be spread by insects and on pruning tools, but is more commonly spread by wind and rain");

            }else if(classes[maxPos].equals("Blast")){
                solutionDiseases.setText("Monitoring and Treatment Decisions Monitor to determine the need for treatments. Throughout the season, examine plants in several locations throughout the field for the presence of leaf lesions; intensify monitoring as plants approach the boot stage. If blast lesions are present and increasing just before the boot stage, a treatment may be justified. When making a treatment decision, consider disease progress, crop growth stage");
            }else if(classes[maxPos].equals("Brownspot")){
                solutionDiseases.setText("Monitoring and Treatment Decisions Monitor to determine the need for treatments. Throughout the season, examine plants in several locations throughout the field for the presence of leaf lesions; intensify monitoring as plants approach the boot stage. If blast lesions are present and increasing just before the boot stage, a treatment may be justified. When making a treatment decision, consider disease progress, crop growth stage");

            }else if(classes[maxPos].equals("Tungro")){
                solutionDiseases.setText("Tungro is caused by the bacterium Pseudomonas syringae pv. syringae (Pss), which survives in diseased stem tissue (cankers), plant debris, and soil. Pss can be spread by insects and on pruning tools, but is more commonly spread by wind and rain");
            }


            // Releases model resources if no longer used.
            dModel.close();
        } catch (IOException e) {
            // TODO Handle the exception
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode == RESULT_OK){
            if(requestCode == 3){
                Bitmap image = (Bitmap) data.getExtras().get("data");
                int dimension = Math.min(image.getWidth(), image.getHeight());
                image = ThumbnailUtils.extractThumbnail(image, dimension, dimension);
                imageView.setImageBitmap(image);

                image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);
                classifyImage1(image);
            }else{
                Uri dat = data.getData();
                Bitmap image = null;
                try {
                    image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), dat);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imageView.setImageBitmap(image);

                image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);
                classifyImage1(image);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}