namespace StorageExperiment

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

import System.*
import System.Storage.Path
import System.Collections.*
import System.IO.*
import System.Text.*
import System.Result.*
import System.Storage.FileReadError
import System.Storage.FileWriteError
import System.Storage.StorageLookupError

// Provider-private byte routing is not part of the platform lookup contract.
interface ByteStorage {
    func OpenRead(path: Path) -> Result<InputStream, StreamError>
    func CreateNew(path: Path) -> Result<OutputStream, StreamError>
}

// Fixture conveniences; consumers of lookup need only System.Storage.StorageProvider.
interface StorageProvider : System.Storage.StorageProvider, ByteStorage {
    func ListItems(path: Path, maxItems: int) -> Result<Sequence<StorageItem>, StorageLookupError>
    func ReadText(path: Path, maxBytes: int) -> Result<string, FileReadError>
    func WriteText(path: Path, text: string, maxBytes: int) -> Result<unit, FileWriteError>
}

class ProviderFile : File {
    private field provider: ByteStorage
    private field path: Path

    init(provider: ByteStorage, path: Path) {
        self.provider = provider
        self.path = path
    }

    val Path: Path => path
    val Name: string => System.Storage.Path.GetFileName(path.Text)

    func OpenRead() -> Result<InputStream, StreamError> {
        return provider.OpenRead(path)
    }

    func CreateNew() -> Result<OutputStream, StreamError> {
        return provider.CreateNew(path)
    }

}

class ProviderDirectory : Directory {
    private field provider: StorageProvider
    private field path: Path

    init(provider: StorageProvider, path: Path) {
        self.provider = provider
        self.path = path
    }

    val Path: Path => path
    val Name: string => System.Storage.Path.GetFileName(path.Text)

    private func Resolve(relativePath: Path) -> Result<Path, StorageLookupError> {
        if relativePath.IsAbsolute {
            return Failure<StorageLookupError>(StorageLookupError.InvalidPath)
        }
        if relativePath.Text == "." {
            return Ok(path)
        }
        var resolved = path.Text + "/" + relativePath.Text
        if path.Text == "/" {
            resolved = "/" + relativePath.Text
        }
        if path.Text == "." {
            resolved = relativePath.Text
        }
        return match System.Storage.Path.Parse(resolved) {
            Ok(let child) => Ok(child)
            Failure(_) => Failure<StorageLookupError>(StorageLookupError.InvalidPath)
        }
    }

    func GetItem(relativePath: Path) -> Result<StorageItem, StorageLookupError> {
        return match Resolve(relativePath) {
            Ok(let child) => provider.GetItem(child)
            Failure(let error) => Failure(error)
        }
    }

    func GetDirectory(relativePath: Path) -> Result<Directory, StorageLookupError> {
        return match Resolve(relativePath) {
            Ok(let child) => provider.GetDirectory(child)
            Failure(let error) => Failure(error)
        }
    }

    func GetDirectory(name: string) -> Result<Directory, StorageLookupError> {
        return match FileAt(name) {
            Ok(let child) => provider.GetDirectory(child.Path)
            Failure(let error) => Failure(error)
        }
    }

    func GetItems(maxItems: int) -> Result<Sequence<StorageItem>, StorageLookupError> {
        return provider.ListItems(path, maxItems)
    }

    // This resolves a direct child address; it does not query existence.
    func FileAt(name: string) -> Result<File, StorageLookupError> {
        if name.IsEmpty || name == "." || name == ".." || name.ContainsOrdinal("/") {
            return Failure<StorageLookupError>(StorageLookupError.InvalidPath)
        }
        var childText = path.Text + "/" + name
        if path.Text == "." {
            childText = name
        }
        if path.Text == "/" {
            childText = "/" + name
        }
        return match System.Storage.Path.Parse(childText) {
            Ok(let child) => {
                let file: File = ProviderFile(provider, child)
                Ok(file)
            }
            Failure(_) => Failure<StorageLookupError>(StorageLookupError.InvalidPath)
        }
    }

    // Validate a direct child, then query its provider. The result owns no stream.
    func GetFile(name: string) -> Result<File, StorageLookupError> {
        return match FileAt(name) {
            Ok(let descriptor) => provider.GetFile(descriptor.Path)
            Failure(_) => Failure<StorageLookupError>(StorageLookupError.InvalidPath)
        }
    }

    // A parsed absolute path is valid syntax, but cannot replace this context.
    func GetFile(relativePath: Path) -> Result<File, StorageLookupError> {
        if relativePath.IsAbsolute {
            return Failure<StorageLookupError>(StorageLookupError.InvalidPath)
        }
        if relativePath.Text == "." {
            return provider.GetFile(path)
        }
        var resolved = path.Text + "/" + relativePath.Text
        if path.Text == "/" {
            resolved = "/" + relativePath.Text
        }
        if path.Text == "." {
            resolved = relativePath.Text
        }
        return match System.Storage.Path.Parse(resolved) {
            Ok(let child) => provider.GetFile(child)
            Failure(_) => Failure<StorageLookupError>(StorageLookupError.InvalidPath)
        }
    }

}

class HostStorage : StorageProvider {
    private field root: string
    private field storage: System.Storage.FileSystem

    init(root: string) {
        self.root = root
        storage = System.Storage.FileSystem(root)
    }

    // Both absolute logical paths and relative paths resolve beneath this root.
    // This is address mapping, not a symlink-safe sandbox.
    private func Resolve(path: Path) -> string {
        let text = path.Text
        if text == "/" || text == "." {
            return root
        }
        if path.IsAbsolute {
            match text.SliceUtf8(1, text.GetUtf8ByteCount() - 1) {
                Ok(let relative) => return System.Storage.Path.Combine(root, relative)
                Failure(_) => Panic("Invalid parsed path boundary")
            }
        }
        return System.Storage.Path.Combine(root, text)
    }

    func GetItem(path: Path) -> Result<StorageItem, StorageLookupError> {
        return storage.GetItem(path)
    }

    func GetDirectory(path: Path) -> Result<Directory, StorageLookupError> {
        return storage.GetDirectory(path)
    }

    func GetFile(path: Path) -> Result<File, StorageLookupError> {
        return storage.GetFile(path)
    }

    func ListItems(path: Path, maxItems: int) -> Result<Sequence<StorageItem>, StorageLookupError> {
        return match storage.GetDirectory(path) {
            Ok(let directory) => directory.GetItems(maxItems)
            Failure(let error) => Failure(error)
        }
    }

    func OpenRead(path: Path) -> Result<InputStream, StreamError> {
        return match FileInputStream.Open(Resolve(path)) {
            Ok(let stream) => {
                let input: InputStream = stream
                Ok(input)
            }
            Failure(let error) => Failure(error)
        }
    }

    func CreateNew(path: Path) -> Result<OutputStream, StreamError> {
        return match FileOutputStream.CreateNew(Resolve(path)) {
            Ok(let stream) => {
                let output: OutputStream = stream
                Ok(output)
            }
            Failure(let error) => Failure(error)
        }
    }

    func ReadText(path: Path, maxBytes: int) -> Result<string, FileReadError> {
        return System.Storage.FileText.ReadAllText(Resolve(path), maxBytes)
    }

    func WriteText(path: Path, text: string, maxBytes: int) -> Result<unit, FileWriteError> {
        return System.Storage.FileText.WriteAllText(Resolve(path), text, maxBytes)
    }
}

// Bounded application-owned provider: one byte payload per logical address.
class MemoryStorage : StorageProvider {
    private field keys: List<string> = ArrayList<string>()
    private field contents: List<List<byte>> = ArrayList<List<byte>>()

    private func Key(path: Path) -> string {
        if path.Text == "." {
            return "/"
        }
        if path.IsAbsolute {
            return path.Text
        }
        return "/" + path.Text
    }

    private func Find(path: Path) -> int {
        let key = Key(path)
        var index = 0
        while index < keys.Count {
            if keys[index] == key {
                return index
            }
            index += 1
        }
        return -1
    }

    // This bounded provider has one directory: its root. Slash-containing keys
    // do not implicitly create a directory tree.
    func ListItems(path: Path, maxItems: int) -> Result<Sequence<StorageItem>, StorageLookupError> {
        if maxItems < 0 {
            return Failure<StorageLookupError>(StorageLookupError.InvalidRange)
        }
        if maxItems > 1024 {
            return Failure<StorageLookupError>(StorageLookupError.LimitExceeded)
        }
        if Key(path) != "/" {
            return Failure<StorageLookupError>(StorageLookupError.NotFound)
        }
        let items: List<StorageItem> = ArrayList<StorageItem>()
        for key in keys {
            match System.Storage.Path.Parse(key) {
                Ok(let child) => {
                    // The bounded fixture has only root children; nested address tests
                    // do not imply a directory tree.
                    let name = System.Storage.Path.GetFileName(key)
                    if key == "/" + name {
                        if items.Count == maxItems {
                            return Failure<StorageLookupError>(StorageLookupError.LimitExceeded)
                        }
                        let item: StorageItem = ProviderFile(self, child)
                        items.Add(item)
                    }
                }
                Failure(_) => Panic("Stored invalid memory key")
            }
        }
        let result: Sequence<StorageItem> = items
        return Ok(result)
    }

    func GetItem(path: Path) -> Result<StorageItem, StorageLookupError> {
        if Key(path) == "/" {
            let directoryItem: StorageItem = ProviderDirectory(self, path)
            return Ok(directoryItem)
        }
        if Find(path) < 0 {
            return Failure<StorageLookupError>(StorageLookupError.NotFound)
        }
        let item: StorageItem = ProviderFile(self, path)
        return Ok(item)
    }

    func GetDirectory(path: Path) -> Result<Directory, StorageLookupError> {
        if Key(path) == "/" {
            let directory: Directory = ProviderDirectory(self, path)
            return Ok(directory)
        }
        if Find(path) >= 0 {
            return Failure<StorageLookupError>(StorageLookupError.WrongKind)
        }
        return Failure<StorageLookupError>(StorageLookupError.NotFound)
    }

    func GetFile(path: Path) -> Result<File, StorageLookupError> {
        if Key(path) == "/" {
            return Failure<StorageLookupError>(StorageLookupError.WrongKind)
        }
        if Find(path) < 0 {
            return Failure<StorageLookupError>(StorageLookupError.NotFound)
        }
        let file: File = ProviderFile(self, path)
        return Ok(file)
    }

    func OpenRead(path: Path) -> Result<InputStream, StreamError> {
        if Key(path) == "/" {
            return Failure<StreamError>(StreamError.WrongKind)
        }
        let index = Find(path)
        if index < 0 {
            return Failure<StreamError>(StreamError.NotFound)
        }
        let stream: InputStream = MemoryInput(contents[index])
        return Ok(stream)
    }

    func CreateNew(path: Path) -> Result<OutputStream, StreamError> {
        if Key(path) == "/" {
            return Failure<StreamError>(StreamError.WrongKind)
        }
        if Find(path) >= 0 {
            return Failure<StreamError>(StreamError.AlreadyExists)
        }
        if keys.Count >= 8 {
            return Failure<StreamError>(StreamError.LimitExceeded)
        }
        let bytes: List<byte> = ArrayList<byte>()
        keys.Add(Key(path))
        contents.Add(bytes)
        let stream: OutputStream = MemoryOutput(bytes)
        return Ok(stream)
    }

    func ReadText(path: Path, maxBytes: int) -> Result<string, FileReadError> {
        if maxBytes < 0 {
            return Failure<FileReadError>(FileReadError.InvalidLimit)
        }
        if Key(path) == "/" {
            return Failure<FileReadError>(FileReadError.NotRegularFile)
        }
        let index = Find(path)
        if index < 0 {
            return Failure<FileReadError>(FileReadError.NotFound)
        }
        let bytes = contents[index]
        if bytes.Count > maxBytes {
            return Failure<FileReadError>(FileReadError.TooLarge)
        }
        return match Utf8.Decode(bytes) {
            Ok(let text) => Ok(text)
            Failure(_) => Failure<FileReadError>(FileReadError.InvalidUtf8)
        }
    }

    func WriteText(path: Path, text: string, maxBytes: int) -> Result<unit, FileWriteError> {
        if maxBytes < 0 {
            return Failure<FileWriteError>(FileWriteError.InvalidLimit)
        }
        if Key(path) == "/" {
            return Failure<FileWriteError>(FileWriteError.NotRegularFile)
        }
        let count = text.GetUtf8ByteCount()
        if count > maxBytes || count > 65536 {
            return Failure<FileWriteError>(FileWriteError.TooLarge)
        }
        let index = Find(path)
        if index < 0 && keys.Count >= 8 {
            // The temporary whole-text error family has no capacity case.
            return Failure<FileWriteError>(FileWriteError.WriteFailed)
        }
        let encoded = Utf8.Encode(text)
        let bytes: List<byte> = ArrayList<byte>()
        var position = 0
        while position < encoded.Count {
            bytes.Add(encoded[position])
            position += 1
        }
        // Publish only after validation/encoding. Existing streams retain old bytes.
        if index < 0 {
            keys.Add(Key(path))
            contents.Add(bytes)
        } else {
            contents[index] = bytes
        }
        return Ok(())
    }
}
