/*
 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.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 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;

    File location;

    @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 i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                try {
                    location = ImageUtils.createTempImageFile();
                } catch (IOException e1) {
                    e1.printStackTrace();
                    return;
                }

                i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(location));
                try {
                    startActivityForResult(i, 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);
                        cachePictureButton.setEnabled(false);
                    }
                }
            });
        }

        if(this.getLastNonConfigurationInstance() != null) {
            location = ((IntentTransferFeatures)this.getLastNonConfigurationInstance()).location;
        }

        if(savedInstanceState != null) {
            location = new File(savedInstanceState.getString("location"));
        }
    }

    @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
                if(location == null || !location.exists()) {
                    location = null;
                } else {
                    String path = location.getAbsolutePath();
                    EarIdentifier identifier = new EarIdentifier(null);
                    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;
    }

}
