<?php

namespace App\Modules\Credential\Domain;

use App\Providers\BookingMailSender;
use Exception;

class CredentialList {

    private $credentialMap;
    private $credentials;

    public function __construct(array $credentials) {
        $this->credentialMap = [];
        $this->credentials = $credentials;
    }

    public function getValue(string $credentialKey):string {
        return $this->get($credentialKey)->Credential_Value;
    }

    public function get(string $credentialKey) {
        if ($this->inMap($credentialKey)) {
            return $this->credentialMap[$credentialKey];
        } else {
            return $this->addToMap($credentialKey);
        }
    }

    private function inMap(string $credentialKey) {
        return array_key_exists($credentialKey, $this->credentialMap);
    }

    private function addToMap (string $credentialKey) {
        $found = BookingMailSender::filterCredential($this->credentials, $credentialKey);
        if (!count($found)) {
            throw new Exception('Credential key ' . $credentialKey . ' doesn\'t exist');
        }
        $this->credentialMap[$found[0]->Credential_key] = $found[0];
        return $found[0];
    }
}