<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\Log;
use Exception;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\RequestException;
use Html2Text\Html2Text;

class ZulipNotifications
{
    /**
     * Send notifications to Zulip when a task has been created.
     *
     * @param  \App\Modules\Bookings\Task $task
     *
     * @return void
     */
    public function created($task)
    {
        $client = new GuzzleClient();
        $html = new Html2Text($task->problem);
		if (! config('services.zulip.username')) {
			return;	
		}
        try {
            Log::info('sending to zulip');
            $client->post(config('services.zulip.url', 'https://your-zulip-server.com') . '/api/v1/messages', [
                'auth' => [
                    config('services.zulip.username'),
                    config('services.zulip.password'),
                ],
                'headers' => [
                    'User-Agent' => 'Seraph/1.0',
                ],
                'body' => [
                    'type'    => 'stream',
                    'to'      => $this->getStream($task->type),
                    'subject' => sprintf('%d-%s', $task->id, $task->title),
                    'content' => sprintf("%s \n\n %s", $this->getHeading($task), $html->getText()),
                ],
                'timeout' => 5, // 5 seconds timeout
            ]);
        } catch (RequestException $e) {
            Log::error($e);
        }
    }

    /**
     * Gets the stream name based on the task type.
     *
     * @param  string $type
     *
     * @return string
     */
    protected function getStream($type)
    {
        switch ($type) {
            // case 'repair': return 'seraph-repairs';
            case 'support': return 'seraph-support';
            // case 'onsite': return 'seraph-onsite';
            case 'qa': return 'seraph-qas';
        }

        return 'seraph';
    }

    /**
     * Get a nicely markdown table formatted heading for the task.
     *
     * @param  \App\Modules\Bookings\Task $task
     *
     * @return string
     */
    protected function getHeading($task)
    {
        try {
            return '| Task Details            |                                                        |
					|-------------------------|-------------------------------------------------------:|
					| '.$task->client->name.' | Created at: '.$task->created_at->format('d/m/Y H:i').' |
					| '.$task->status->name.' | Booked by: '.$task->creator->name.'                    |';
        } catch (Exception $e) {
            return '';
        }
    }
}
