#!/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

%exec-class DirTest

class DirTest inherits QUnit::Test {
    constructor() : QUnit::Test("Dir", "1.0") {
        addTestCase("DirTest", \dirTest());
        addTestCase("issue3192 test", \issue3192Test());
        set_return_value(main());
    }

    dirTest() {
        string dir1 = sprintf(tmp_location() + DirSep + get_random_string());
        Dir d();
        bool b = d.chdir(dir1);
        assertEq(False, b);
        int rc = d.create();
        on_exit
            rmdir(dir1);
        assertEq(1, rc);
        assertEq("DIRECTORY", hstat(dir1).type);

        string dir2 = get_random_string();
        string dir3 = get_random_string();
        b = d.chdir(dir2);
        assertEq(False, b);
        b = d.chdir(dir3);
        assertEq(False, b);
        rc = d.create();
        string path2 = dir1 + DirSep + dir2;
        string path3 = dir1 + DirSep + dir2 + DirSep + dir3;
        on_exit {
            rmdir(path3);
            rmdir(path2);
        }
        assertEq(2, rc);
        assertEq("DIRECTORY", hstat(path3).type);
        assertEq("DIRECTORY", hstat(path2).type);

%ifdef HAVE_STATVFS
        hash<auto> h = d.statvfs();
        assertEq("hash<FilesystemInfo>", h.fullType());
%endif
    }

    issue3192Test() {
%ifdef Windows
        testSkip("skipping because the test is being run on Windows");
%endif

        # create temp dir
        string tmpdirPath = sprintf(tmp_location() + DirSep + "qoretest" + get_random_string());
        Dir d();
        bool b = d.chdir(tmpdirPath);
        assertEq(False, b);
        int rc = d.create();
        on_exit system("rm -rf " + tmpdirPath + "/*");

        # create random file
        string fileA = get_random_string() + "A";
        string aPath = tmpdirPath + DirSep + fileA;
        {
            File f();
            f.open2(aPath, O_CREAT | O_WRONLY | O_TRUNC);
            f.write("abc\n");
            f.close();
        }
        on_exit system("rm -f " + aPath);

        # create symlink with non-existent target
        string linkName = get_random_string() + "_link";
        string linkPath = tmpdirPath + DirSep + linkName;
        string targetName = "sdjfksdfjksf";
        rc = system("ln -s " + targetName + " " + linkPath);
        if (rc)
            fail();
        on_exit system("rm -f " + linkPath);

        assertEq(sort((fileA, linkName)), sort(d.list()));
        list<string> files = d.listFiles();
        assertEq((fileA,), files);
        assertEq(list(), d.listDirs());
    }
}
