package doglet.text;

import nova.*;

import java.time.DayOfWeek;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.*;

/**
 * Warranty & Liability
 * To the extent permitted by applicable law and unless explicitly
 * otherwise agreed upon, XLOG Technologies AG makes no warranties
 * regarding the provided information. XLOG Technologies AG assumes
 * no liability that any problems might be solved with the information
 * provided by XLOG Technologies AG.
 *
 * Rights & License
 * All industrial property rights regarding the information - copyright
 * and patent rights in particular - are the sole property of XLOG
 * Technologies AG. If the company was not the originator of some
 * excerpts, XLOG Technologies AG has at least obtained the right to
 * reproduce, change and translate the information.
 *
 * Reproduction is restricted to the whole unaltered document. Reproduction
 * of the information is only allowed for non-commercial uses. Selling,
 * giving away or letting of the execution of the library is prohibited.
 * The library can be distributed as part of your applications and libraries
 * for execution provided this comment remains unchanged.
 *
 * Restrictions
 * Only to be distributed with programs that add significant and primary
 * functionality to the library. Not to be distributed with additional
 * software intended to replace any components of the library.
 *
 * Trademarks
 * Jekejeke is a registered trademark of XLOG Technologies AG.
 */

public final class intlib {

    /******************************************************************/
    /* os_atom_time/4                                                */
    /******************************************************************/

    /**
     * os_atom_time(A, F, O, T): internal only
     * If A is a variable, the built-in succeeds in A with the millisecond
     * time T formatted by the pattern F and the flag O. Otherwise the
     * built-in succeeds in T with the millisecond time parsed from A
     * by the pattern F and the flag O.
     */
    private static boolean test_os_atom_time(Object[] args) {
        Object fmt = Machine.exec_build(args[1]);
        special.check_atom(fmt);
        Object flag = Machine.exec_build(args[2]);
        special.check_integer(flag);
        Object text = Machine.exec_deref(args[0]);
        if (Store.is_variable(text) || Machine.is_pending(text)) {
            Object obj = Machine.exec_build(args[3]);
            special.check_integer(obj);
            if (!theatre.is_long((Number) obj))
                throw Machine.make_error(new Store.Compound("representation_error",
                        new Object[]{"long", obj}));
            long tms = ((Number) obj).longValue();
            String res;
            try {
                res = sys_time_format((String) fmt, tms,
                        ((Number) flag).intValue());
            } catch (IllegalArgumentException x) {
                throw Machine.make_error(new Store.Compound("domain_error",
                        new Object[]{"time_format", fmt}));
            }
            return Machine.exec_unify(text, res);
        } else {
            text = Machine.exec_build(text);
            special.check_atom(text);
            long tms;
            try {
                tms = theatre.sys_time_parse((String) text, (String) fmt,
                        ((Number) flag).intValue());
            } catch (NumberFormatException x) {
                throw Machine.make_error(new Store.Compound("syntax_error",
                        new Object[]{"illegal_date"}));
            } catch (IllegalArgumentException x) {
                throw Machine.make_error(new Store.Compound("domain_error",
                        new Object[]{"time_format", fmt}));
            }
            return Machine.exec_unify(args[3], special.norm_smallint(tms));
        }
    }

    /**
     * Format a date time string.
     *
     * @param pat The format pattern.
     * @param tms The date time in UTC milliseconds.
     * @param utc The UTC calendar flag.
     * @return The date time as a string.
     */
    public static String sys_time_format(String pat, long tms, int utc) {
        Calendar cal;
        if (utc != 0) {
            cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        } else {
            cal = Calendar.getInstance();
        }
        cal.setTimeInMillis(tms);
        StringBuilder buf = new StringBuilder();
        int k = 0;
        for (int i = 0; i < pat.length(); i++) {
            char ch = pat.charAt(i);
            if (ch == '%') {
                buf.append(pat, k, i);
                i++;
                if (i < pat.length()) {
                    switch (pat.charAt(i)) {
                        case '%':
                            buf.append('%');
                            break;
                        case 'a':
                            int j = cal.get(Calendar.DAY_OF_WEEK);
                            DayOfWeek wday = DayOfWeek.of((j != 1 ? j - 1 : 7));
                            buf.append(wday.getDisplayName(TextStyle.SHORT_STANDALONE,
                                    (utc != 0 ? Locale.US : Locale.getDefault())));
                            break;
                        case 'b':
                            Month mon = Month.of(cal.get(Calendar.MONTH) + 1);
                            buf.append(mon.getDisplayName(TextStyle.SHORT_STANDALONE,
                                    (utc != 0 ? Locale.US : Locale.getDefault())));
                            break;
                        case 'd':
                            append_padded(buf, cal.get(Calendar.DAY_OF_MONTH));
                            break;
                        case 'm':
                            append_padded(buf, cal.get(Calendar.MONTH) + 1);
                            break;
                        case 'Y':
                            buf.append(cal.get(Calendar.YEAR));
                            break;
                        case 'H':
                            append_padded(buf, cal.get(Calendar.HOUR_OF_DAY));
                            break;
                        case 'M':
                            append_padded(buf, cal.get(Calendar.MINUTE));
                            break;
                        case 'S':
                            append_padded(buf, cal.get(Calendar.SECOND));
                            break;
                        default:
                            throw new IllegalArgumentException("illegal format");
                    }
                    k = i + 1;
                } else {
                    k = i;
                }
            }
        }
        buf.append(pat, k, pat.length());
        return buf.toString();
    }

    /**
     * Append an integer value zero padded.
     *
     * @param buf   The string builder.
     * @param value The integer value.
     */
    private static void append_padded(StringBuilder buf, int value) {
        if (value < 10)
            buf.append('0');
        buf.append(value);
    }

    /******************************************************************/
    /* Int Lib Init                                                   */
    /******************************************************************/

    public static void main() {
        Store.set("os_atom_time", 4, special.make_check(intlib::test_os_atom_time));
    }

}