<?php

namespace Dipper\Excel;

use Dipper\Excel\Events\Event;
use Dipper\Excel\Events\AfterSheet;
use Dipper\Excel\Events\AfterStore;
use Dipper\Excel\Events\AfterExport;
use Dipper\Excel\Events\BeforeSheet;
use Dipper\Excel\Events\BeforeExport;
use Dipper\Excel\Events\BeforeWriting;

trait RegistersCustomConcerns
{
    /**
     * @var array
     */
    private static $eventMap = [
        BeforeWriting::class => Writer::class,
        BeforeExport::class  => Writer::class,
        BeforeSheet::class   => Sheet::class,
        AfterSheet::class    => Sheet::class,
        AfterExport::class  => Writer::class,
        AfterStore::class  => Writer::class,
    ];

    /**
     * @param string   $concern
     * @param callable $handler
     * @param string   $event
     */
    public static function extend(string $concern, callable $handler, string $event = BeforeWriting::class)
    {
        /** @var HasEventBus $delegate */
        $delegate = static::$eventMap[$event] ?? BeforeWriting::class;

        $delegate::listen($event, function (Event $event) use ($concern, $handler) {
            if ($event->appliesToConcern($concern)) {
                $handler($event->getConcernable(), $event->getDelegate());
            }
        });
    }
}
