<?php

namespace Bixo\Team\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Team\Events\TeamAction as TeamActionEvent;
use Bixo\Team\Notifications\TeamAction as TeamActionNotification;
use Litepie\Actions\Concerns\AsAction;

class TeamAction
{
    use AsAction;

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

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

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

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

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