<?php

namespace Bixo\Location\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Location\Events\BuildingAction as BuildingActionEvent;
use Bixo\Location\Notifications\BuildingAction as BuildingActionNotification;
use Litepie\Actions\Concerns\AsAction;

class BuildingAction
{
    use AsAction;

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

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

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

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

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