<?php

namespace Cronard;

use Notes\Cronard\TaskFetcher;

use Psr\Container\ContainerInterface;

use Psr\Http\Message\ResponseInterface,
    Psr\Http\Message\ServerRequestInterface;

trait CronardTrait {

    public array $crontabs = [];

    public function launch(array $variables) : void
    {
        $cronard = new Cronard();

        foreach($this->crontabs as $tab) {
            $cronard->setTab(stripslashes($tab['cron']));
            $cronard->run(array_merge($this->variables, $variables), $tab['callback']);
        }
    }

    public function fromFile(string $filepath) : self
    {
        if ( ! file_exists($filepath) ) {
            throw new \RuntimeException("Given crontab file cannot be found. There could also be a problem at permission level.");
        }

        foreach(include($filepath) as $tab => $callback) {
            $this->crontabs[] = [
                'cron' => $tab,
                'callback' => $callback,
            ];
        }

        return $this;
    }

    public function fromAnnotations(TaskFetcher $fetcher) : self
    {
        $tasks = [];

        foreach($fetcher->compile() as $task) {
            $this->crontabs[] = [
                'cron' => $task['annotation']->cron,
                'callback' => function(ServerRequestInterface $request, ResponseInterface $response, ContainerInterface $container) use ($task) {
                    if ( $task['annotation']->method ?? false ) {
                        $request = $request->withMethod($task['annotation']->method);
                    }

                    return $container->make($task['class'])->{$task['method']}($request->withAttribute('lean.cronard', $task['annotation']), []);
                }
            ];
        }

        return $this;
    }
}