package org.javarosa.xpath.expr;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.xform.util.CalendarUtils;
import org.javarosa.xpath.XPathUnsupportedException;
import org.javarosa.xpath.parser.XPathSyntaxException;

import java.util.Date;

public class XPathFormatDateForCalendarFunc extends XPathFuncExpr {
    public static final String NAME = "format-date-for-calendar";
    private static final int EXPECTED_ARG_COUNT = 2;

    public XPathFormatDateForCalendarFunc() {
        name = NAME;
        expectedArgCount = EXPECTED_ARG_COUNT;
    }

    public XPathFormatDateForCalendarFunc(XPathExpression[] args) throws XPathSyntaxException {
        super(NAME, args, EXPECTED_ARG_COUNT, true);
    }

    @Override
    public Object evalBody(DataInstance model, EvaluationContext evalContext) {
        return formatDateForCalendar(evaluatedArgs[0], evaluatedArgs[1]);
    }

    /**
     * Given a date and format, return that date as a string formatted for that calendar
     * Accepted calendars are Ethiopian and Nepali
     *
     * @param dateObject The Object (String, Date, or XPath) to be evaluated into a date
     * @param format     The calendar format (nepali or ethiopian)
     */
    private static String formatDateForCalendar(Object dateObject, Object format) {

        Date date = FunctionUtils.expandDateSafe(dateObject);
        if (date == null) {
            return "";
        }
        if ("ethiopian".equals(format)) {
            return CalendarUtils.ConvertToEthiopian(date);
        } else if ("nepali".equals(format)) {
            return CalendarUtils.convertToNepaliString(date);
        } else {
            throw new XPathUnsupportedException("Unsupported calendar type: " + format);
        }
    }

    @Override
    public String getDocumentation() {
        return "?";
    }
}

@@ -1891,10 +1891,446 @@
 urn 
-%22?
+getDocHeader()%0A                + %22Behavior: Converts a Gregorian formatted date to a different calendar format. %5Cn%22%0A                + %22Return: a String of the input date formatted for the specified calendar. %5Cn%22%0A                + %22Arguments: The date to be converted and the format to convert to %22%0A                    + %22(currently 'ethiopian' or 'nepali'). %5Cn%22%0A                + %22Example: format-date-for-calendar('19070-01-1', 'nepali')
 %22;%0A 

add format-date-for-calendar docs