namespace StorageExperiment

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

import System.*
import System.Collections.*
import System.Result.*
import System.IO.*
import System.Text.*

func WriteMessage(output: OutputStream) -> Result<unit, StreamError> {
    let message = Utf8.Encode("Hello, värld!")
    let buffer: byte[] = [(byte)0, (byte)0, (byte)0]
    var position = 0
    while position < message.Count {
        var count = 0
        while count < buffer.Length && position < message.Count {
            buffer[count] = message[position]
            count += 1
            position += 1
        }
        var offset = 0
        while offset < count {
            match output.Write(buffer, offset, count - offset) {
                Ok(let written) => {
                    if written <= 0 || written > count - offset {
                        Panic("Invalid write progress")
                    }
                    offset += written
                }
                Failure(let error) => return Failure(error)
            }
        }
    }
    return output.Flush()
}

func ReadMessage(input: InputStream) -> Result<List<byte>, StreamError> {
    let bytes: List<byte> = ArrayList<byte>()
    let buffer: byte[] = [(byte)0, (byte)0, (byte)0]
    var finished = false
    while !finished {
        match input.Read(buffer, 0, buffer.Length) {
            Ok(let count) => {
                if count == 0 {
                    finished = true
                }
                if count > 64 - bytes.Count {
                    return Failure<StreamError>(StreamError.LimitExceeded)
                }
                var index = 0
                while index < count {
                    bytes.Add(buffer[index])
                    index += 1
                }
            }
            Failure(let error) => return Failure(error)
        }
    }
    return Ok(bytes)
}

func ByteRoundTrip(directory: Directory, provider: StorageProvider) {
    match directory.FileAt("stream.txt") {
        Ok(let file) => {
            match file.CreateNew() {
                Ok(let output) => {
                    let written = WriteMessage(output)
                    // Close before inspecting either success or expected failure.
                    output.Close()
                    output.Close()
                    match written {
                        Ok(_) => { }
                        Failure(let error) => Panic(error.ToString())
                    }
                    match output.Flush() {
                        Failure(let error) => {
                            if !(error is System.IO.StreamError.Closed) {
                                Panic("Expected closed output")
                            }
                        }
                        Ok(_) => Panic("Closed output flushed")
                    }
                }
                Failure(let error) => Panic(error.ToString())
            }
            match file.CreateNew() {
                Failure(let error) => {
                    if !(error is System.IO.StreamError.AlreadyExists) {
                        Panic("Expected exclusive creation")
                    }
                }
                Ok(let unexpected) => {
                    unexpected.Close()
                    Panic("Creation replaced an existing file")
                }
            }
            match file.OpenRead() {
                Ok(let input) => {
                    let read = ReadMessage(input)
                    input.Close()
                    input.Close()
                    match read {
                        Ok(let bytes) => {
                            match Utf8.Decode(bytes) {
                                Ok(let text) => {
                                    if text != "Hello, värld!" {
                                        Panic("Byte stream changed the message")
                                    }
                                    Console.WriteLine("Byte stream round trip: " + text)
                                }
                                Failure(let error) => Panic(error.ToString())
                            }
                        }
                        Failure(let error) => Panic(error.ToString())
                    }
                    let buffer: byte[] = [(byte)99]
                    match input.Read(buffer, 0, 1) {
                        Failure(let error) => {
                            if !(error is System.IO.StreamError.Closed) || buffer[0] != (byte)99 {
                                Panic("Expected closed input with untouched buffer")
                            }
                        }
                        Ok(_) => Panic("Closed input read")
                    }
                }
                Failure(let error) => Panic(error.ToString())
            }
            match provider.ReadText(file.Path, 14) {
                Ok(let text) => {
                    if text != "Hello, värld!" {
                        Panic("Byte writes not visible through text helper")
                    }
                }
                Failure(let error) => Panic(error.ToString())
            }
            Console.WriteLine("Byte stream write visible through text helper")
            Console.WriteLine("Exclusive creation and closed streams checked")
        }
        Failure(let error) => Panic(error.ToString())
    }
}

// Fixture assertion helper: decode the small, known UTF-8 contract-test contents.
func ReadFileText(file: File) -> Result<string, StreamError> {
    match file.OpenRead() {
        Ok(let input) => {
            let read = ReadMessage(input)
            input.Close()
            match read {
                Ok(let bytes) => {
                    match Utf8.Decode(bytes) {
                        Ok(let text) => return Ok(text)
                        Failure(_) => Panic("Expected UTF-8 fixture contents")
                    }
                }
                Failure(let error) => return Failure(error)
            }
        }
        Failure(let error) => return Failure(error)
    }
    return Failure<StreamError>(StreamError.IoFailure)
}
