<?php declare(strict_types=1);

require_once __DIR__ . '/../../data/QrbProtocolEntry.php';
require_once __DIR__ . '/../../common/QrbException.php';

final class QrbProtocolFile
{
    // Writes the given protocol entries to disk.
    // (Does not create a protocol file if given protocol is empty.)
    // If an old file with the same name exists, the old file is deleted first.
    //
    // fileName: name of protocol file
    // protocol: array of QrbProtocolEntry
    //
    // Returns false if file is not written as there are no entries.
    //
    // Throws QrbException if store fails.
    public function write(string $fileName, array $protocol) : bool
    {
        if (!($protocol) || (count($protocol) == 0))
            return false;

        $fileName = $fileName;
        
        if (file_exists($fileName))
            if (! unlink($fileName))
                throw new QrbException(static::class . " - Unable to delete old protocol file '{$fileName}'",
                                       "exception.files.unableToDeleteFile",
                                       $fileName);

        if (($protocolFileHandle = fopen($fileName, "w")) === false)
            throw new QrbException(static::class . " - Unable to open protocol file '{$fileName}'",
                                   "exception.files.unableToOpenFile",
                                   $fileName);
            
        foreach ($protocol as $entry)
        {
            if (fputcsv($protocolFileHandle, $entry->toArray()) === false)
                throw new QrbException(static::class . " - Unable to write to protocol file",
                                       "exception.files.unableToWriteFile",
                                       $fileName);
        }
        
        if (!fflush($protocolFileHandle))
            throw new QrbException(static::class . " - Unable to flush protocol file",
                                   "exception.files.unableToFlushFile".
                                   $fileName);
                                   
        if (!fclose($protocolFileHandle) )
            throw new QrbException(static::class . " - Unable to close protocol file",
                                   "exception.files.unableToCloseFile".
                                   $fileName);
                                   
        return true;
    }
}

?>
