<?php

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Helper\Slack;
use App\Entity\Order;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Notifier\ChatterInterface;

class SlackNotifySubscriber implements EventSubscriberInterface
{
    /**
     * @var Slack
     */
    public $slack;
    public $logger;

//    public function __construct(ChatterInterface $chatter, LoggerInterface $logger)
//    {
//        $this->slack = new Slack($chatter);
//        $this->logger = $logger;
//    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['sendSlack', EventPriorities::POST_WRITE],
        ];
    }


    /**
     * @param ViewEvent $event
     * @return void
     */
    public function sendSlack(ViewEvent $event): void
    {
        $order = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        $this->logger->info('SlackNotifySubscriber: ' . $method);
        //$this->logger->info('SlackNotifySubscriber: ' . $order);

        //wenn es keine Bestellung ist oder es kein POST Request ist, dann return
        if (!$order instanceof Order || Request::METHOD_POST !== $method) {
            return;
        }

       $msg = "Order {$order->getId()} has been created: {$order->getStatus()}";
       $this->slack->sendMessage($msg);

    }
}