<?php

namespace Signteer\Core;

use Plainwork\Core\App;
use Plainwork\Database\Migrator;
use Plainwork\DateTime\TimeFactory;
use Plainwork\DateTime\DateTimeFormatter;
use Signteer\Core\Event\EventBus;

final class Boot
{
    public function __construct(App $app)
    {
        $app->onBoot(Migrator::class, function ($migrator) {
            $migrator
                ->register('setting', 1, [Database\SettingTable::class, 'up1'], [Database\SettingTable::class, 'down1'])
                ->register('sheet', 1, [Database\SheetTable::class, 'up1'], [Database\SheetTable::class, 'down1'])
                ->register('task', 1, [Database\TaskTable::class, 'up1'], [Database\TaskTable::class, 'down1'])
                ->register('signup', 1, [Database\SignupTable::class, 'up1'], [Database\SignupTable::class, 'down1'])
                ->register('signup_field', 1, [Database\SignupFieldTable::class, 'up1'], [Database\SignupFieldTable::class, 'down1'])
                ->register('volunteer', 1, [Database\VolunteerTable::class, 'up1'], [Database\VolunteerTable::class, 'down1'])
            ;
        });

        $app->onBoot(DateTimeFormatter::class, function ($dtf) use ($app) {
            $setting = $app->make(Repo\SettingRepo::class);

            $timeFormat = $setting->get('datetime_time_format');
            if (null !== $timeFormat) {
                $dtf->setTimeFormat($timeFormat);
            }

            $dateFormat = $setting->get('datetime_date_format');
            if (null !== $dateFormat) {
                $dtf->setDateFormat($dateFormat);
            }
        });

        $app->onBoot(TimeFactory::class, function ($timeFactory) use ($app) {
            $setting = $app->make(Repo\SettingRepo::class);

            $weekStartsOn = $setting->get('datetime_week_starts');
            if (null !== $weekStartsOn) {
                $timeFactory->setWeekStartsOn($weekStartsOn);
            }
        });

        $app->onBoot(EventBus::class, function ($eventBus) {
            $eventBus
                // ->listenAll(Service\EventLogger::class)
                ->listen(Event\Signup\SignupCreated::class, [Listener\Signup\NotifyVolunteer::class, 'onCreate'])
                // ->listen(Event\Signup\SignupDeleted::class, [Listener\Signup\NotifyVolunteer::class, 'onDelete'])
            ;

            $eventBus
                ->register(Event\Setting\SettingsUpdated::class)
            ;
        });
    }
}
