/*
 * @Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

package memorycache

import std.fs.*
import std.io.*
import std.posix
import std.fs

class FileUtils {
    public static let SEPARATOR: String = "/"
    public static var sInstance = FileUtils()
    private var BASE64Str: String = ""

    private init() {}

    public static func getInstance() {
        return sInstance
    }

    public func createFile(path: String) {
        File.create(path)
    }

    public func deleteFile(path: String) {
        if (fs.exists(path)) {
            fs.remove(path)
        } else {
            throw MemoryCacheException("File not found")
        }
    }

    public func exists(path: String): Bool {
        return fs.exists(path)
    }

    public func writeNewFile(path: String, data: String) {
        if (!this.exists(path)) {
            this.createFile(path)
        }
        this.writeFile(path, data)
    }

    public func writeNewFile(path: String, data: Array<UInt8>) {
        if (!this.exists(path)) {
            this.createFile(path)
        }
        this.writeFile(path, data)
    }

    public func getFileSize(path: String): Int64 {
        var file = File(path, OpenMode.Read)
        var size = file.length
        file.close()
        return size
    }

    public func readFile(path: String): Array<UInt8> {
        if (posix.isDir(path)) {
            return Array<UInt8>()
        }
        var file = File(path, OpenMode.Read)
        var arr = readToEnd(file)
        file.close()
        return arr
    }

    public func createFolder(path: String, recursive!: Bool) {
        if (!exists(path)) {
            Directory.create(path, recursive: recursive)
        }
    }

    public func existFolder(path: String): Bool {
        exists(path)
    }

    public func writeFile(path: String, data: Array<UInt8>) {
        var file = File(path, OpenMode.Append)
        file.write(data)
        file.close()
    }

    public func writeFile(path: String, data: String) {
        var file = File(path, OpenMode.Append)
        file.write(data.toArray())
        file.close()
    }
}