namespace StorageExperiment

import System.Storage.File
import System.Storage.Directory

import System.*
import System.Console.*
import System.Result.*
import System.Text.*

// This workflow receives a directory; it does not select the storage provider.
func RoundTrip(directory: Directory, provider: StorageProvider) {
    match directory.FileAt("notes.txt") {
        Ok(let file) => {
            WriteLine(file.Name)
            match provider.WriteText(file.Path, "Hello, värld!", 14) {
                Ok(_) => WriteLine("Written")
                Failure(let error) => Panic(error.ToString())
            }
            match provider.ReadText(file.Path, 14) {
                Ok(let text) => WriteLine(text)
                Failure(let error) => Panic(error.ToString())
            }
            match provider.WriteText(file.Path, "too large", 2) {
                Failure(let error) => {
                    if !(error is System.Storage.FileWriteError.TooLarge) {
                        Panic("Wrong bounded-write error")
                    }
                }
                Ok(_) => Panic("Oversized write succeeded")
            }
            match provider.ReadText(file.Path, 14) {
                Ok(let text) => {
                    if text != "Hello, värld!" {
                        Panic("Rejected write changed contents")
                    }
                }
                Failure(let error) => Panic(error.ToString())
            }
            match provider.ReadText(file.Path, 13) {
                Failure(let error) => {
                    if !(error is System.Storage.FileReadError.TooLarge) {
                        Panic("Wrong UTF-8 byte-limit error")
                    }
                }
                Ok(_) => Panic("Byte limit counted characters")
            }
            match file.OpenRead() {
                Ok(let input) => {
                    let result = ReadMessage(input)
                    input.Close()
                    match result {
                        Ok(let bytes) => {
                            match Utf8.Decode(bytes) {
                                Ok(let text) => {
                                    if text != "Hello, värld!" {
                                        Panic("Text and byte reads disagree")
                                    }
                                }
                                Failure(_) => Panic("Written text was not valid UTF-8")
                            }
                        }
                        Failure(let error) => Panic(error.ToString())
                    }
                }
                Failure(let error) => Panic(error.ToString())
            }
            WriteLine("Text write visible through byte stream")
            WriteLine("Rejected write preserved contents")
        }
        Failure(let error) => Panic(error.ToString())
    }
}

func RejectChild(directory: Directory, name: string) {
    match directory.FileAt(name) {
        Failure(let error) => {
            if !(error is System.Storage.StorageLookupError.InvalidPath) {
                Panic("Wrong child-name error")
            }
        }
        Ok(_) => Panic("Invalid child name accepted")
    }
}

func Main() {
    let host: StorageProvider = HostStorage("sandbox")
    let memory: StorageProvider = MemoryStorage()
    // Parsing does not open storage. The same logical root works for both providers.
    let root = RequirePath("/")
    let disk = RequireDirectory(host, root)
    let temporary = RequireDirectory(memory, root)
    WriteLine("Disk")
    RoundTrip(disk, host)
    ByteRoundTrip(disk, host)
    WriteLine("Memory")
    RoundTrip(temporary, memory)
    ByteRoundTrip(temporary, memory)
    for directory in [disk, temporary] {
        match directory.GetFile("notes.txt") {
            Ok(let file) => {
                if file.Name != "notes.txt" {
                    Panic("Lookup lost the child name")
                }
                match ReadFileText(file) {
                    Ok(let text) => {
                        if text != "Hello, värld!" {
                            Panic("Lookup changed provider ownership")
                        }
                    }
                    Failure(let error) => Panic(error.ToString())
                }
            }
            Failure(let error) => Panic(error.ToString())
        }
    }
    WriteLine("File lookup reads the same contents on disk and memory")
    match temporary.FileAt("notes.txt") {
        Ok(let file) => {
            if !file.Path.Equals(RequirePath("/notes.txt")) {
                Panic("Directory replaced the provider address")
            }
            match ReadFileText(file) {
                Ok(let text) => {
                    if text != "Hello, värld!" {
                        Panic("A new descriptor lost provider state")
                    }
                }
                Failure(let error) => Panic(error.ToString())
            }
        }
        Failure(let error) => Panic(error.ToString())
    }
    RejectChild(disk, "../outside.txt")
    RejectChild(disk, "")
    RejectChild(disk, ".")
    RejectChild(disk, "..")
    RejectChild(disk, "child/name")
    RejectChild(disk, "child\\name")
    RejectChild(disk, "child\u0000name")
    WriteLine("Direct child required")
    let otherMemory: StorageProvider = MemoryStorage()
    let other = ProviderFile(otherMemory, RequirePath("/notes.txt"))
    match otherMemory.ReadText(other.Path, 64) {
        Failure(let error) => {
            if !(error is System.Storage.FileReadError.NotFound) {
                Panic("Wrong missing-file error")
            }
            WriteLine("Providers remain independent")
        }
        Ok(_) => Panic("Provider state leaked")
    }
}
