<?php

namespace Shikiryu\Bot;

class Bot
{
    protected Request $request;
    protected array $events = [];
    protected array $config = [];
    protected static array $masters = [];

    protected function getMaster(): string
    {
        $masters = array_merge(self::$masters, $this->getConfig()['masters']);
        return $masters[array_rand($masters)];
    }

    public function __construct(Request $request, array $config = [])
    {
        $this->request = $request;
        $this->config = $config;
    }

    /**
     * @param string          $pattern  the pattern to listen for
     * @param \Closure|string $callback the callback to execute. Either a closure or a Class@method notation
     *
     * @return $this
     */
    public function hears(string $pattern, \Closure|string $callback): static
    {
        if (!array_key_exists($pattern, $this->events)) {
            $this->events[$pattern] = $callback;
        }

        return $this;
    }

    /**
     * Try to match messages with the ones we should
     * listen to.
     */
    public function listen($sentence): void
    {
        foreach ($this->events as $pattern => $command) {
            $preg_pattern = sprintf('#%s#i', $pattern);
            if (preg_match($preg_pattern, $sentence, $matches)) {
                if (is_callable($command)) {
                    call_user_func($command, $this);
                } else {
                    call_user_func([$command, 'getMessage'], $this, $matches);
                }
                return;
            }
        }

        $this->replyPolitely('Je n\'ai pas compris');
    }

    public function replyPolitely(string $message): void
    {
        $message .= ', '.$this->getMaster().'.';
        $this->reply($message);
    }

    public function sendChatMessage(string $referenceId, string $message): void {
        $body = [
            'message' => $message,
            'referenceId' => $referenceId,
        ];

        $jsonBody = json_encode($body, JSON_THROW_ON_ERROR);

        $random = bin2hex(random_bytes(32));
        $hash = hash_hmac('sha256', $random . $message, $this->config['secret']);

        $ch = curl_init(rtrim($this->config['url'], '/') . '/ocs/v2.php/apps/spreed/api/v1/bot/' . $this->config['conversation'] . '/message');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonBody);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'alfred/1.0');
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'OCS-APIRequest: true',
            'Content-Type: application/json',
            'X-Nextcloud-Talk-Bot-Random: ' . $random,
            'X-Nextcloud-Talk-Bot-Signature: ' . $hash,
        ]);
        curl_exec($ch);
        curl_close($ch);
    }

    public function reply(string $message): void
    {
        $this->sendChatMessage('', $message);
    }

    public function getConfig(): array
    {
        return $this->config;
    }

    public function listCommands(): \Generator
    {
        $commands_folder = __DIR__.DIRECTORY_SEPARATOR.'Commands';
        foreach (scandir($commands_folder) as $command) {
            if ($command === '.' || $command === '..' || $command === 'Icommands.php') {
                continue;
            }
            $class_name = explode('.', $command)[0];
            yield sprintf('Shikiryu\Bot\Commands\%s', $class_name);
        }
    }
}
