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

%new-style
%enable-all-warnings
%require-types
%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 Data1 = ("type": "type1", "record": ("col1" : 11111, "col2" : "bb"));

        const Data2 = (
            ("type": "type1", "record": ("col1" : 11111, "col2" : "bb")),
            ("type": "type2", "record": ("col3" : "c", "col4" : "ddd", "col5" : "31122014")),
            ("type": "type1", "record": ("col1" : 22222, "col2" : "gg")),
            );

        const DataText = "11111bb\n11111bb\ncddd31122014\n22222gg\n";

        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" : "Europe/Prague",
                ),
            ),
            );

        const GlobalOptions = (
            "eol": "\n",
            "file_flags": O_CREAT | O_WRONLY | O_TRUNC,
            );
    }

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

    basicTests() {
        string file = tmp_location() + "/file.fll";

        {
            FixedLengthFileWriter w(file, Specs, GlobalOptions);
            on_exit unlink(file);
            w.write(Data1);
            w.write(Data2);

            testAssertionValue("file content check", ReadOnlyFile::readTextFile(file), DataText);
        }
        {
            FixedLengthFileWriter w(file, Specs, GlobalOptions + ("eol": "\r\n"));
            on_exit unlink(file);
            w.write(Data1);
            w.write(Data2);

            testAssertionValue("file content check", ReadOnlyFile::readTextFile(file), replace(DataText, "\n", "\r\n"));
        }
    }
}
