#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

%require-types
%enable-all-warnings
%new-style
%strict-args

%requires ../../../../qlib/Util.qm
%requires ../../../../qlib/QUnit.qm
%requires ../../../../qlib/DataProvider
%requires ../../../../qlib/FixedLengthUtil

%exec-class Test

class Test inherits QUnit::Test {
    public {
        const Specs = (
            "type1" : (
                "col1" : (
                    "length" : 5,
                    "type"   : "int"
                ),
                "col2" : (
                    "length" : 2,
                    "type"   : "string",
                ),
            ),
            "type2" : (
                "col3" : (
                    "length" : 1,
                    "type"   : "string",
                ),
                "col4" : (
                    "length" : 3,
                    "type"   : "string",
                ),
                "col5" : (
                    "length"   : 8,
                    "type"     : "date",
                    "format"   : "DDMMYYYY",
                    #"timezone" : "UTC", # use global if omitted
                ),
            ),
            );

        hash GlobalOptions = (
            "encoding"     : "UTF-8",
            "eol"          : "\n",
            "ignore_empty" : True,
            "timezone"     : "UTC", # used if not overridden in date field specifications
            );
    }

    constructor() : QUnit::Test("FixedLengthFileIterator", "1.0", \ARGV) {
        addTestCase("FixedLengthFileIterator basic tests", \basicTests());
        set_return_value(main());
    }

    basicTests() {
        string file = tmp_location() + "/file.fll";
        unlink(file);
        {
            File FW();
            FW.open2(file, O_WRONLY | O_CREAT);
            FW.write("11111bb\ncddd31122014\n\n\n22222gg\n");
        }
        on_exit unlink(file);

        FixedLengthFileIterator i(file, Specs, GlobalOptions);
        assertEq(True, i.hasCallableMethod("hstat"));
        assertEq(True, i.hasCallableMethod("stat"));
        assertEq(True, i.hasCallableMethod("getFileName"));
        assertEq(True, i.hasCallableMethod("getEncoding"));
        testAssertionValue("line 1 is there", i.next(), True);
        testAssertionValue("line 1 content check", i.getValue(), ("type": "type1", "record": ("col1" : 11111, "col2" : "bb")));
        testAssertionValue("line 2 is there", i.next(), True);
        testAssertionValue("line 2 content check", i.getValue(), ("type": "type2", "record": ("col3" : "c", "col4" : "ddd", "col5" : 2014-12-31Z)));
        testAssertionValue("line 3 is there", i.next(), True);
        testAssertionValue("line 3 content check", i.getValue(), ("type": "type1", "record": ("col1" : 22222, "col2" : "gg")));
        testAssertionValue("line 4 is not there", i.next(), False);
    }
}
