package com.aluxoft.earrecognition.activities;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;

import com.aluxoft.earrecognition.EarIdentifier;
import com.aluxoft.earrecognition.R;
import com.aluxoft.earrecognition.common.EarData;
import com.aluxoft.earrecognition.common.EarFeature;
import com.aluxoft.earrecognition.common.EarIdList;
import com.aluxoft.earrecognition.common.NameDistance;
import com.aluxoft.earrecognition.common.Person;
import com.aluxoft.earrecognition.loader.EarDataLoaderCommcare;
import com.aluxoft.earrecognition.utils.FileCache;
import com.google.gson.Gson;

import java.io.File;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;

/**
 * Computes SIFT & finds top-n matches
 * TODO: Get other users features, compare SIFT features, etc...
 */
public class SIFTActivity extends Activity {

    final int kTopN = 7;

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

        ProgressDialog loading = ProgressDialog.show(SIFTActivity.this,
                "Searching matches", "Please wait while we search for matches...");
        loading.setCancelable(false);
        loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        Task.callInBackground(new Callable<EarIdList>() {
            @Override
            public EarIdList call() throws Exception {
                // Sift
                EarIdentifier identifier = new EarIdentifier(null);
                Intent intent = SIFTActivity.this.getIntent();
                Bundle extras = intent.getExtras();
                String imagePath = (String)extras.get("image_path");
                EarFeature earFeature = identifier.computeFeatures(imagePath);

                File imageFile = new File(imagePath);

                FileCache.getFile(
                        SIFTActivity.this.getApplicationContext(),
                        FileCache.FileCacheType.Image)
                        .replaceContent(imageFile);
                FileCache
                        .getFile(SIFTActivity.this, FileCache.FileCacheType.Features)
                        .replaceContent(earFeature.serializeFeatures());

                // Once we have the features, we can delete the image.
                imageFile.delete();

                // Compares the current features with the database.
                EarData data = new EarDataLoaderCommcare().load(SIFTActivity.this);
                data.computeDistance(earFeature);

                ArrayList<NameDistance> distances = new ArrayList<>(data.getPersons().values());
                Collections.sort(distances);

                EarIdList result = new EarIdList();
                List<NameDistance> topN = distances.subList(0, Math.min(kTopN, distances.size()));
                result.setTop(topN);

                // Pass results to next activity.
                result.setCurrentFeature(earFeature);
                return result;

            }
        }).continueWith(new Continuation<EarIdList, Object>() {
            @Override
            public Object then(Task<EarIdList> task) throws Exception {
                Intent intent = new Intent("com.auriclon.activity_select_user");
                intent.putExtra("list", new Gson().toJson(task.getResult()));
                setResult(0, intent);
                finish();
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);

    }
}
