<?php

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Order;
use App\Repository\ProductRepository;
use App\Repository\StockRepository;
use App\Repository\WarehouseRepository;

use Maknz\Slack\Client;
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;


class SlackNotifySubscriber implements EventSubscriberInterface
{
    /**
     * @var Slack
     */
    private $slackWebhookUrl;
    private $productRepository;
    private $stockRepository;
    private $warehouseRepository;


    public function __construct(string $slackWebhookUrl, ProductRepository $productRepository, StockRepository $stockRepository, WarehouseRepository $warehouseRepository)
    {
        $this->slackWebhookUrl = $slackWebhookUrl;
        $this->productRepository = $productRepository;
        $this->stockRepository = $stockRepository;
        $this->warehouseRepository = $warehouseRepository;

    }

    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();

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

            foreach ($order->getData()[0]['positions'] as $item) {
                if ($item['menge'] > 0) {

                    $warehouse = $this->getWarehouseByGtin($item['gtin']);

                    if ($warehouse == false) {
                        continue;
                    }

                    $slack = new Client($this->slackWebhookUrl, [
                        'username' => 'CDS-Notify',
                        'channel' => '#online_verkäufe' . '_' . $warehouse,
                        'link_names' => true,
                        'icon' => ':robot_face:',
                        'allow_markdown' => true,
                    ]);

                    $msg = "Bestellung {$order->getOrderId()}: \n";
                    $msg .= $item['marke'] . ' - ';
                    $msg .= $item['name'];
                    $msg .= ' - ' . $item['han'];
                    $msg .= ' * - ' . $item['menge'] . "* \n";


                    $slack->from('CDS-Notify')->send($msg);

                }
            }
        }
    }

    /**
     * @param string $gtin
     * @return array
     */
    private function getWarehouseByGtin(string $gtin)
    {
        if ($gtin == null) {
            return false;
        }
        $warehouse = "";

        $product = $this->productRepository->findOneBy(['gtin' => $gtin]);

        if ($product) {
            $stock = $this->stockRepository->findBy(['product_id' => $product->getId()]);

            if ($stock) {
                $prio = 0;
                foreach ($stock as $item) {
                    //Nur wenn Bestand vorhanden
                    if ($item->getInstock() > 0) {
                        $w = $this->warehouseRepository->findOneBy(['id' => $item->getWarehouse()->getId()]);

                        if ($w->getPrio() > $prio) {
                            $warehouse = $w->getName();
                            $prio = $w->getPrio();
                        }
                    }
                }
            }
        }

        return $warehouse;

    }
}