<?php

namespace FacturaScripts\Plugins\Partes\Services\Task;

use FacturaScripts\Dinamic\Model\TareaProyecto;

class TaskContext
{
    private array $post;
    private array $files;
    private ?TareaProyecto $task = null;
    private bool $isNewTask = false;
    private array $subtaskTargets = [];

    public function __construct(array $post, array $files)
    {
        $this->post = $post;
        $this->files = $files;
    }

    public static function fromRequest(array $post, array $files): self
    {
        return new self($post, $files);
    }

    public function shouldProcess(): bool
    {
        return !empty($this->post['update_task']);
    }

    public function get(string $key, $default = null)
    {
        return $this->post[$key] ?? $default;
    }

    public function set(string $key, $value): void
    {
        $this->post[$key] = $value;
    }

    public function allPost(): array
    {
        return $this->post;
    }

    public function replacePost(array $data): void
    {
        $this->post = $data;
    }

    public function files(): array
    {
        return $this->files;
    }

    public function isNewFlagged(): bool
    {
        return !empty($this->post['esNuevaTarea']);
    }

    public function setTask(TareaProyecto $task, bool $isNew): void
    {
        $this->task = $task;
        $this->isNewTask = $isNew;
    }

    public function task(): TareaProyecto
    {
        if (null === $this->task) {
            throw new \RuntimeException('Task has not been prepared.');
        }
        return $this->task;
    }

    public function hasTask(): bool
    {
        return $this->task !== null;
    }

    public function isNewTask(): bool
    {
        return $this->isNewTask;
    }

    public function addSubtaskTarget($rawId, int $targetId): void
    {
        $this->subtaskTargets[(string) $rawId] = $targetId;
    }

    public function setSubtaskTargets(array $targets): void
    {
        $this->subtaskTargets = $targets;
    }

    public function getSubtaskTargets(): array
    {
        return $this->subtaskTargets;
    }
}
