/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/
 */
package org.phenotips.data.internal.controller;

import org.phenotips.data.Patient;
import org.phenotips.data.PatientData;
import org.phenotips.data.PatientDataController;
import org.phenotips.data.SimpleValuePatientData;

import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.component.annotation.Component;
import org.xwiki.context.Execution;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import org.slf4j.Logger;

import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;

import net.sf.json.JSONObject;

/**
 * Handles the patient's date of birth and the exam date.
 *
 * @version $Id$
 * @since 1.0M10
 */
@Component(roles = { PatientDataController.class })
@Named("lifestatus")
@Singleton
public class LifeStatusController implements PatientDataController<String>
{
    private static final String DATA_NAME = "life_status";

    private static final String PATIENT_CHECKBOX_FIELDNAME = "date_of_death_unknown";

    private static final String PATIENT_DATEOFDEATH_FIELDNAME = DatesController.PATIENT_DATEOFDEATH_FIELDNAME;

    private static final String ALIVE = "alive";

    private static final String DECEASED = "deceased";

    private static final Set<String> ALL_LIFE_STATES = new HashSet<String>(Arrays.asList(ALIVE, DECEASED));

    /** Logging helper object. */
    @Inject
    private Logger logger;

    /** Provides access to the underlying data storage. */
    @Inject
    private DocumentAccessBridge documentAccessBridge;

    /** Provides access to the current execution context. */
    @Inject
    private Execution execution;

    @Override
    public PatientData<String> load(Patient patient)
    {
        try {
            XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument());
            BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE);
            if (data == null) {
                throw new NullPointerException("The patient does not have a PatientClass");
            }

            String lifeStatus = ALIVE;
            Date date = data.getDateValue(PATIENT_DATEOFDEATH_FIELDNAME);
            if (date != null) {
                lifeStatus = DECEASED;
            } else {
                // check if "unknown death date" checkbox is checked
                Integer deathDateUnknown = data.getIntValue(PATIENT_CHECKBOX_FIELDNAME);
                if (deathDateUnknown != 0) {
                    lifeStatus = DECEASED;
                }
            }
            return new SimpleValuePatientData<String>(DATA_NAME, lifeStatus);
        } catch (Exception e) {
            this.logger.error("Could not find requested document or some unforeseen"
                + " error has occurred during controller loading ", e.getMessage());
        }
        return null;
    }

    @Override
    public void save(Patient patient)
    {
        try {
            XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument());
            BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE);
            if (data == null) {
                throw new NullPointerException(ERROR_MESSAGE_NO_PATIENT_CLASS);
            }

            PatientData<String> lifeStatus = patient.getData(DATA_NAME);
            PatientData<Date> dates = patient.getData("dates");

            Integer deathDateUnknown = 0;
            if (lifeStatus != null && lifeStatus.getValue() == DECEASED) {
                deathDateUnknown = 1;
            }
            if (dates != null && dates.isNamed()) {
                // check if death_date is set - if it is unknown_death_date should be unset
                Date deathDate = dates.get(PATIENT_DATEOFDEATH_FIELDNAME);
                if (deathDate != null) {
                    deathDateUnknown = 0;
                }
                return;
            }

            data.setIntValue(PATIENT_CHECKBOX_FIELDNAME, deathDateUnknown);

            XWikiContext context = (XWikiContext) this.execution.getContext().getProperty("xwikicontext");
            context.getWiki().saveDocument(doc, "Updated dates from JSON", true, context);
        } catch (Exception e) {
            this.logger.error("Failed to save dates: [{}]", e.getMessage());
        }
    }

    @Override
    public void writeJSON(Patient patient, JSONObject json)
    {
        writeJSON(patient, json, null);
    }

    @Override
    public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames)
    {
        PatientData<String> lifeStatusData = patient.getData(DATA_NAME);
        if (lifeStatusData == null) {
            return;
        }
        json.put(DATA_NAME, lifeStatusData.getValue());
    }

    @Override
    public PatientData<String> readJSON(JSONObject json)
    {
        String propertyValue = json.optString(DATA_NAME, null);
        if (propertyValue != null) {
            // validate - only accept listed values
            if (ALL_LIFE_STATES.contains(propertyValue)) {
                return new SimpleValuePatientData<String>(DATA_NAME, propertyValue);
            }
        }
        return null;
    }

    @Override
    public String getName()
    {
        return DATA_NAME;
    }
}

@@ -1099,44 +1099,8 @@
 ent;
-%0Aimport org.xwiki.context.Execution;
 %0A%0Aim
@@ -1278,16 +1278,46 @@
 .Named;%0A
+import javax.inject.Provider;%0A
 import j
@@ -2543,27 +2543,39 @@
 ate 
-Execution execution
+Provider%3CXWikiContext%3E xcontext
 ;%0A%0A 
@@ -4920,122 +4920,27 @@
     
-XWikiContext context = (XWikiContext) this.execution.getC
+this.xc
 ontext
-()
 .get
-Property(%22xwikicontext%22);%0A            context
+()
 .get
@@ -4973,20 +4973,26 @@
 Updated 
-date
+life statu
 s from J
@@ -5003,23 +5003,35 @@
 , true, 
+this.x
 context
+.get()
 );%0A     

Use Provider<XWikiContext> instead of the Execution to access the old XWikiContext