<?php declare(strict_types=1);

require_once __DIR__ . '/../storage/QrbStorage.php';
require_once __DIR__ . '/../data/QrbProtocolEntry.php';
require_once __DIR__ . '/../data/QrbRecipient.php';

// Helper to write the QR bill protocol.
final class QrbProtocol
{
    private QrbStorage $qrbStorage;
    
    private array $protocol = [];   // array of QrbProtocolEntry
    
    // Creates an instance of the QR bill protocol.
    //
    // qrbStorage: storage interface, used to store the protocol
    public function __construct(QrbStorage $qrbStorage)
    {
        $this->qrbStorage = $qrbStorage;
    }

    // Creates an entry for the given recipient and adds it to the in-memory list 
    // (but does not persist the protocol).
    //
    // recipient: current recipient, used to create the QrbProtocolEntry
    // 
    // Returns an instance of QrbProtocolEntry.
    public function createEntry(QrbRecipient $recipient) : QrbProtocolEntry
    {
        $entry = new QrbProtocolEntry($recipient);
        $this->protocol += [ $recipient->getIndex() => $entry ];
        return $entry;
    }

    // Stores the in-memory list of the created protocol entries.
    //
    // Returns a string containing the relative path to the current protocol
    // or NULL in the case the protocol is not written (empty or dryRun).
    // 
    // Throws QrbException if store fails.
    public function write() : ?string
    {
        return $this->qrbStorage->writeProtocol($this->protocol);
    }

    public function __toString()
    {
        $result = "Contents of protocol:";       
        
        foreach ($this->protocol as $entry)
        {
            $result .= "\n===";
            $result .= $entry;
        }
        
        return $result;
    }
}

?>
