var fd = use("fd")
var miniz = use("miniz")
var utf8 = use("utf8")

return {
    create_and_read_zip: function() {
        var ZIP_PATH = "miniz_test.zip"
        var SOURCE_PATH = "miniz_source.txt"
        var ENTRY_PATH = "sample/hello.txt"
        var PAYLOAD = "Miniz integration test payload."
        var source_blob = null
        var writer = null
        var zip_blob = null
        var reader = null
        var extracted_blob = null
        var extracted_text = null

        function write_text_file(path, txt) {
          var handle = fd.open(path, "w")
          fd.write(handle, txt)
          fd.close(handle)
        }

        var _run = function() {
          write_text_file(SOURCE_PATH, PAYLOAD)
          source_blob = fd.slurp(SOURCE_PATH)
          writer = miniz.write(ZIP_PATH)
          writer.add_file(ENTRY_PATH, source_blob)
          writer = null

          zip_blob = fd.slurp(ZIP_PATH)
          reader = miniz.read(zip_blob)

          if (!reader.exists(ENTRY_PATH))
            disrupt

          extracted_blob = reader.slurp(ENTRY_PATH)
          extracted_text = utf8.decode(extracted_blob)

          if (extracted_text != PAYLOAD)
            disrupt
        } disruption {}
        _run()

        var _clean1 = function() { fd.unlink(ZIP_PATH) } disruption {}
        _clean1()
        var _clean2 = function() { fd.unlink(SOURCE_PATH) } disruption {}
        _clean2()
    },

    list_and_count: function() {
        var ZIP_PATH = "miniz_list_test.zip"
        var ENTRY1 = "file1.txt"
        var ENTRY2 = "dir/file2.txt"
        var writer = null
        var zip_blob = null
        var reader = null
        var listed = null

        var _run = function() {
          writer = miniz.write(ZIP_PATH)
          writer.add_file(ENTRY1, utf8.encode("content1"))
          writer.add_file(ENTRY2, utf8.encode("content2"))
          writer = null

          zip_blob = fd.slurp(ZIP_PATH)
          reader = miniz.read(zip_blob)

          listed = reader.list()
          if (length(listed) != reader.count())
            disrupt
          if (length(listed) != 2)
            disrupt
        } disruption {}
        _run()

        var _clean = function() { fd.unlink(ZIP_PATH) } disruption {}
        _clean()
    },

    exists_check: function() {
        var ZIP_PATH = "miniz_exists_test.zip"
        var ENTRY_PATH = "existing.txt"
        var writer = null
        var zip_blob = null
        var reader = null

        var _run = function() {
          writer = miniz.write(ZIP_PATH)
          writer.add_file(ENTRY_PATH, utf8.encode("data"))
          writer = null

          zip_blob = fd.slurp(ZIP_PATH)
          reader = miniz.read(zip_blob)

          if (!reader.exists(ENTRY_PATH))
            disrupt
          if (reader.exists("nonexistent.txt"))
            disrupt
        } disruption {}
        _run()

        var _clean = function() { fd.unlink(ZIP_PATH) } disruption {}
        _clean()
    }
}
