<?php

namespace Signteer\Core\Writer;

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

class TaskWriter
{
    public $db = Database::class;

    public function create(int $sheetId, string $title, int $spots): int
    {
        $q = $this->db->q();

        $q->insertInto(Table::NAME);
        $q->valueString(Table::COL_TITLE, $title);
        $q->valueInt(Table::COL_SHEET_ID, $sheetId);
        $q->valueInt(Table::COL_SPOTS, $spots);

        $id = $q->execute();

        return $id;
    }

    public function delete(int $id)
    {
        $q = $this->db->q();

        $q->deleteFrom(Table::NAME);
        $q->whereInt(Table::COL_ID, '=', $id);

        $q->execute();
    }

    public function update(int $id, ?string $title, ?int $spots)
    {
        if (null !== $title or null !== $spots) {
            $q = $this->db->q();

            $q->update(Table::NAME);
            if (null !== $title) {
                $q->valueString(Table::COL_TITLE, $title);
            }
            if (null !== $spots) {
                $q->valueInt(Table::COL_SPOTS, $spots);
            }
            $q->whereInt(Table::COL_ID, '=', $id);

            $q->execute();
        }
    }
}
