package com.aluxoft.earrecognition.loader;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;

import com.aluxoft.earrecognition.common.EarData;
import com.aluxoft.earrecognition.common.EarFeature;
import com.aluxoft.earrecognition.common.Person;

/**
 * Created by josejuliomartinez on 13/10/15.
 */
public class EarDataLoaderCommcare extends EarDataLoader {

    @Override
    public EarData load(Activity current) {

        EarData earData = new EarData();

        Cursor c = current.managedQuery(Uri.parse("content://org.commcare.dalvik.case/casedb/case"), null, null, null, null);

        if (c == null) {
            // Throw an exception (Unable to connect to commcare)
            return earData;
        }

        String caseId;
        String name;
        String gender;
        String features;

        while (c.moveToNext()) {
            caseId = c.getString(c.getColumnIndex("case_id"));
            name = c.getString(c.getColumnIndex("case_name"));
            gender = null;
            features = null;

            Uri uri = Uri.parse("content://org.commcare.dalvik.case/casedb/data/" + caseId);
            Cursor caseCursor = current.managedQuery(uri, null, null, null, null);
            if (caseCursor == null) {
                continue;
            }
            while (caseCursor.moveToNext()) {
                String datumId = caseCursor.getString(caseCursor.getColumnIndex("datum_id"));
                if (datumId.equals("gender")) {
                    gender = caseCursor.getString(caseCursor.getColumnIndex("value"));
                } else if (datumId.equals("features")) {
                    features = caseCursor.getString(caseCursor.getColumnIndex("value"));
                }
            }
            if (gender == null || features == null) {
                continue;
            }
            Person person = new Person();
            person.setCaseId(caseId);
            person.setName(name);
            person.setGender(gender);
            person.addFeature(new EarFeature(features));
            earData.addPerson(person);
        }

        return earData;
    }
}
