<?php

namespace Edulab\College\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Edulab\College\Events\GuardianAction as GuardianActionEvent;
use Edulab\College\Notifications\GuardianAction as GuardianActionNotification;
use Litepie\Actions\Concerns\AsAction;

class GuardianAction
{
    use AsAction;

    private $allowedActions = [
        'before' => [],
        'after' => ['create'],
    ];

    /**
     * Handle the GuardianActionEvent.
     *
     * @param   GuardianActionEvent  $event
     * @return mixed
     */
    public function handle(GuardianActionEvent $event)
    {
        $function = Str::camel($event->action);
        return $this->$function($event);
    }

    /**
     * Create a new $guardian.
     *
     * @param   GuardianActionEvent  $event
     * @return void
     */
    public function create(GuardianActionEvent $event)
    {
        $client = $event->guardian->client;
        Notification::send($client, new GuardianActionNotification($event));
    }

    /**
     * Handle the GuardianActionEvent as a listener.
     *
     * @param   GuardianActionEvent  $event
     * @return mixed
     */
    public function asListener(GuardianActionEvent $event)
    {
        if ($this->isAllowed($event)) {
            return $this->handle($event);
        }
    }

    /**
     * Check if the event action is allowed.
     *
     * @param   GuardianActionEvent  $event
     * @return bool
     */
    private function isAllowed(GuardianActionEvent $event)
    {
        if ($event->when == 'before' &&
            !in_array($event->action, $this->allowedActions['before'])) {
            return false;
        }

        if (($event->when == 'after' &&
            !in_array($event->action, $this->allowedActions['after']))
        ) {
            return false;
        }

        return true;
    }
}