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.EarIdList;
import com.aluxoft.earrecognition.loader.EarDataLoaderCommcare;
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;

/**
 * Callout to transfer features to CommCare
 */
public class IntentTransferingFeatures 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);

        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);
        }


        if (this.findViewById(R.id.current_picture) != null) {
            final Button button = (Button) this.findViewById(R.id.current_picture);
            ImageView image = (ImageView) this.findViewById(R.id.image);
            image.setImageDrawable(Drawable.createFromPath(imageCache.getAbsolutePath()));
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        _showTransferringMessage();
                        Intent returningIntent = new Intent(getIntent());
                        returningIntent.putExtra(
                                "odk_intent_data",
                                FileUtils.readFileToString(
                                        FileCache
                                                .getFile(IntentTransferingFeatures.this.getApplicationContext(),
                                                        FileCache.FileCacheType.Features)
                                )

                        );
                        IntentTransferingFeatures.this.setResult(Activity.RESULT_OK, returningIntent);
                        finish();
                    } catch (Exception e) {
                        Toast.makeText(IntentTransferingFeatures.this, "An error occurred when loading the features.", Toast.LENGTH_LONG);
                        button.setEnabled(false);
                    }
                }
            });
        }

        this.findViewById(R.id.take_picture).setOnClickListener(new View.OnClickListener() {

            private Toast loginInCommCareToast = null;

            public void onClick(View v) {
                if (!EarDataLoaderCommcare.checkConnection(IntentTransferingFeatures.this)) {

                    if (loginInCommCareToast == null || loginInCommCareToast.getView().getWindowVisibility() != View.VISIBLE) {
                        loginInCommCareToast = Toast.makeText(IntentTransferingFeatures.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) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    return;
                }

                // if this gets modified, the onActivityResult in
                // FormEntyActivity will also need to be updated.
                i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(location));
                try {
                    startActivityForResult(i, KEY_REQUEST_IMAGE);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(IntentTransferingFeatures.this, "No Camera", Toast.LENGTH_SHORT).show();
                }
            }

        });

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

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

    /* (non-Javadoc)
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == KEY_REQUEST_IMAGE) {
            //Go grab the image and set it's location
            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) {
            _showTransferringMessage();
            String list = data.getStringExtra("list");
            EarIdList earIdList = new Gson().fromJson(list, EarIdList.class);
            Intent returningIntent = new Intent(getIntent());
            returningIntent.putExtra(
                    "odk_intent_data",
                    earIdList.getCurrentFeature().serializeFeatures()
            );
            IntentTransferingFeatures.this.setResult(Activity.RESULT_OK, returningIntent);
            finish();
        }
    }

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

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

}
