<?php

namespace Edulab\College\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Edulab\College\Events\StudentAction as StudentActionEvent;
use Edulab\College\Notifications\StudentAction as StudentActionNotification;
use Litepie\Actions\Concerns\AsAction;

class StudentAction
{
    use AsAction;

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

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

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

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

    /**
     * Check if the event action is allowed.
     *
     * @param   StudentActionEvent  $event
     * @return bool
     */
    private function isAllowed(StudentActionEvent $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;
    }
}