<?php

namespace App\Notification\Providers;

use App\Notification\NotificationProvider;
use App\Models\JobInfo;
use Illuminate\Support\Facades\Cache;

class DiscordWebHookNotification extends NotificationProvider {

    private const EMBED_COLOR = ["521254", "16058119"];

    /**
     * @inheritDoc
     */
    public static function send(\App\Notification\Notification $notification, array $options): void {
        /*
            Test Json for a complete embed :
            {
                "content": "",
                "tts": false,
                "embeds": [
                    {
                    "id": 652627557,
                    "title": "Title",
                    "description": "This is the markdown body\n",
                    "color": 521254,
                    "fields": [
                        {
                        "id": 984079152,
                        "name": "Field 1",
                        "value": "test"
                        }
                    ],
                    "url": "https://localhost:8000",
                    "image": {
                        "url": "https://www.thoughtco.com/thmb/jzJO77P0K9zIbqxQOVOaHWFCfj4=/1732x1732/filters:fill(auto,1)/GettyImages-186451154-58c3965a3df78c353cf8cc7b.jpg"
                    }
                    }
                ],
                "components": [],
                "actions": {},
                "username": "Datboi",
                "avatar_url": "https://www.fairytailrp.com/t40344-here-come-dat-boi"
            }
        */
        $webHookUrl = static::getDiscordWebHookUrl($notification->isError, $options);
        $body = [
            "content"=> "",
            "tts"=> false,
            "embeds" => [
                [
                    "id" => 652627557,
                    "title" => $notification->getTitle()->toString(),
                    "description" => $notification->getBody()->toMarkdownString(),
                    "color" => self::EMBED_COLOR[(int)$notification->isError],
                    "url" => $notification->getLinkURL(),
                ],
            ],
            "username" => "Datboi",
            "avatar_url" => "https://media1.giphy.com/media/yDTWAecZcB2Jq/200w.gif?cid=6c09b952f68kz3wnkqsmyha8e7xrpe8n2kx0nkf2b8cir6am&rid=200w.gif&ct=g",
        ];

        if ($notification->getImageURL() !== null) {
            $body["embeds"][0]["image"] = [
                "url" => "attachment://image.png"
            ];
        }

        $payloadJson = json_encode($body);

        $formData = [
            'payload_json' => $payloadJson,
        ];

        if ($notification->getImageURL() !== null && is_file($notification->getImageProjectPath())) {
            $formData['file'] = curl_file_create($notification->getImageProjectPath(), 'image/png', 'image.png');
        }

        $ch = curl_init($webHookUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $formData);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if (!curl_exec($ch)) {
            $error = curl_error($ch);
            \Log::error("Discord WebHook Notification failed: {$error}");
            throw new \Exception("Discord WebHook Notification failed: {$error}");
        }
        curl_close($ch);
    }

    private static function getDiscordWebHookUrl(bool $isError, array $options): string {
        if (isset($options["discord_webhook_url"]) && $options["discord_webhook_url"] !== null) {
            return $options["discord_webhook_url"];
        }

        $generalWebHookUrlKey = 'discord_webhook_url';
        $generalWebHookUrl = Cache::rememberForever($generalWebHookUrlKey,  function () use ($generalWebHookUrlKey) {
            return JobInfo::where('key', $generalWebHookUrlKey)->first()->value;
        });
        if ($generalWebHookUrl === null) {
            throw new \Exception("Le webhook discord n'a pas été configuré");
        }

        if ($isError) {
            $errorWebHookUrlKey = 'discord_error_webhook_url';
            $errorWebHookUrl = Cache::rememberForever($errorWebHookUrlKey,  function () use ($errorWebHookUrlKey) {
                return JobInfo::where('key', $errorWebHookUrlKey)->first()->value;
            });
            return $errorWebHookUrl ?? $generalWebHookUrl;
        }
        else {
            return $generalWebHookUrl;
        }
    }
}
