<?php

namespace Signteer\Core\Repo;

use Plainwork\Database\Database;
use Plainwork\Database\Query;
use Signteer\Core\Database\SettingTable as Table;

class SettingRepo
{
    public $db = Database::class;
    public $table = Table::class;
    private ?array $original = null;

    public function get(string $name): ?string
    {
        $this->load();

        return $this->original[$name] ?? null;
    }

    public function set(string $name, string $value)
    {
        $this->load();

        if (array_key_exists($name, $this->original)) {
            if ($value === $this->original[$name]) {
                return;
            }
        }

        $q = $this->db->q();
        if (array_key_exists($name, $this->original)) {
            $q->update(Table::NAME);
            $q->valueString(Table::COL_VALUE, $value);
            $q->whereString(Table::COL_NAME, '=', $name);
        } else {
            $q->insertInto(Table::NAME);
            $q->valueString(Table::COL_NAME, $name);
            $q->valueString(Table::COL_VALUE, $value);
        }
        $q->execute();
    }

    private function load()
    {
        if (null !== $this->original) {
            return;
        }

        $this->original = [];

        $q = $this->db->q();
        $q->select(Table::COL_NAME);
        $q->select(Table::COL_VALUE);
        $q->from(Table::NAME);

        try {
            $res = $q->execute();
            foreach ($res as $row) {
                $this->original[$row[Table::COL_NAME]] = $row[Table::COL_VALUE];
            }
        } catch (\Exception $e) {
        }
    }
}
