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

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

import com.aluxoft.earrecognition.common.PatientHashMap;
import com.aluxoft.earrecognition.common.EarFeature;
import com.aluxoft.earrecognition.common.Patient;

public class PatientLoaderCommcare {

    public static boolean checkConnection(Activity current) {
        Cursor c = current.managedQuery(Uri.parse("content://org.commcare.dalvik.case/casedb/case"), null, null, null, null);
        return c != null;
    }

    public PatientHashMap load(Activity current) {

        PatientHashMap patientHashMap = new PatientHashMap();

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

        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"));
                } else if (datumId.equals("ear_id")) { // ToDo: Remplazarlo con una mejor forma
                    caseId = caseCursor.getString(caseCursor.getColumnIndex("value"));
                }
            }
            if (/*gender == null || */features == null) {
                continue;
            }
            Patient patient = new Patient();
            patient.setCaseId(caseId);
            patient.setName(name);
            patient.setGender(gender);
            patient.addFeature(new EarFeature(features));
            patientHashMap.addPatient(patient);
        }

        return patientHashMap;
    }
}
