/*
 Copyright by Boston University, 2016
 Authors: Josejulio Martínez, Daniel Kornhauser
 Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 */
package com.aluxoft.earrecognition.intents;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.aluxoft.earrecognition.EarIdentifier;
import com.aluxoft.earrecognition.R;
import com.aluxoft.earrecognition.common.TopMatchesList;
import com.aluxoft.earrecognition.loader.PatientLoaderCommcare;
import com.aluxoft.earrecognition.utils.FileCache;
import com.aluxoft.earrecognition.utils.ImageUtils;
import com.google.gson.Gson;
import com.yalantis.cameramodule.activity.BasePhotoActivity;
import com.yalantis.cameramodule.activity.CameraActivity;

import org.apache.commons.io.FileUtils;


import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Entry point for fetching the features of a photo.
 *
 * Takes the photo, sends to SIFT activity and returns.
 */
public class IntentTransferFeatures extends Activity {

    public static final int KEY_REQUEST_IMAGE = 1;
    public static final int KEY_SIFT_ACTIVITY_LOADER = 2;

    private ProgressDialog loading;

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

        // Getting picture from cache and checking if is valid
        FileCache imageCache = FileCache.getFile(this.getApplicationContext(), FileCache.FileCacheType.Image);
        FileCache featuresCache = FileCache.getFile(this.getApplicationContext(), FileCache.FileCacheType.Features);
        if (imageCache.isValid() && featuresCache.isValid()) {
            setContentView(R.layout.activity_callout_with_features);
        } else {
            setContentView(R.layout.activity_callout);
        }

        // Creating the takePictureButton
        Button takePictureButton = (Button) this.findViewById(R.id.take_picture);
        takePictureButton.setOnClickListener(new View.OnClickListener() {
            private Toast loginInCommCareToast = null;

            @Override
            public void onClick(View v) {
                if (!PatientLoaderCommcare.checkConnection(IntentTransferFeatures.this)) {
                    if (loginInCommCareToast == null || loginInCommCareToast.getView().getWindowVisibility() != View.VISIBLE) {
                        loginInCommCareToast = Toast.makeText(IntentTransferFeatures.this,
                                "Please login in CommCare application to proceed.",
                                Toast.LENGTH_LONG);
                        loginInCommCareToast.show();
                    }
                    return;
                }
                Intent intent = new Intent(IntentTransferFeatures.this, CameraActivity.class);
                intent.putExtra(CameraActivity.PATH, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
                intent.putExtra(CameraActivity.OPEN_PHOTO_PREVIEW, true);
                intent.putExtra(CameraActivity.USE_FRONT_CAMERA, false);

                try {
                    startActivityForResult(intent, KEY_REQUEST_IMAGE);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(IntentTransferFeatures.this, "No Camera", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // If there is a valid picture in cache, we display the photo and
        // create a cachePictureButton to pass back to CommCare
        if (this.findViewById(R.id.current_picture) != null) {
            final Button cachePictureButton = (Button) this.findViewById(R.id.current_picture);
            ImageView image = (ImageView) this.findViewById(R.id.image);
            image.setImageDrawable(Drawable.createFromPath(imageCache.getAbsolutePath()));
            cachePictureButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        _showTransferringMessage();
                        Intent returningIntent = new Intent(getIntent());

                        Bundle responses = new Bundle();
                        responses.putString("ear_id", UUID.randomUUID().toString());
                        returningIntent.putExtra("odk_intent_bundle", responses);

                        returningIntent.putExtra(
                                "odk_intent_data",
                                FileUtils.readFileToString(
                                        FileCache
                                                .getFile(IntentTransferFeatures.this.getApplicationContext(),
                                                        FileCache.FileCacheType.Features)
                                )
                        );
                        IntentTransferFeatures.this.setResult(Activity.RESULT_OK, returningIntent);
                        finish();
                    } catch (Exception e) {
                        Toast.makeText(IntentTransferFeatures.this,
                                "An error occurred when loading the features.", Toast.LENGTH_LONG).show();
                        cachePictureButton.setEnabled(false);
                    }
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == KEY_REQUEST_IMAGE) {
            // Pass image location to SIFT activity
            // Go grab the image and set it's location
            String filePath = data.getStringExtra(BasePhotoActivity.EXTRAS.PATH);
            if (filePath != null) {
                File location = new File(filePath);
                if (location != null && location.exists()) {
                    String path = location.getAbsolutePath();
                    Intent intent = new Intent("com.auriclon.activity_sift");
                    intent.putExtra("image_path", path);
                    startActivityForResult(intent, KEY_SIFT_ACTIVITY_LOADER);
                }
            }
        } else if (requestCode == KEY_SIFT_ACTIVITY_LOADER) {
            // Fetches features from SIFT activity to return to CommCare
            _showTransferringMessage();
            String list = data.getStringExtra("list");
            TopMatchesList topMatchesList = new Gson().fromJson(list, TopMatchesList.class);
            Intent returningIntent = new Intent(getIntent());

            Bundle responses = new Bundle();
            responses.putString("ear_id", UUID.randomUUID().toString());
            returningIntent.putExtra("odk_intent_bundle", responses);

            returningIntent.putExtra(
                    "odk_intent_data",
                    topMatchesList.getCurrentFeature().serializeFeatures()
            );
            IntentTransferFeatures.this.setResult(Activity.RESULT_OK, returningIntent);
            finish();
        }
    }

    private void _showTransferringMessage() {
        loading = ProgressDialog.show(IntentTransferFeatures.this,
                "Transferring", "Please wait while transferring the features...");
        loading.setCancelable(false);
        loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    }

    private void _closeTransferringMesagge() {
        loading.dismiss();
        loading = null;
    }

}
