<?php

declare(strict_types=1);

namespace Seka\Terminy\Services\External\Calendar\Google;

use Koksosk\Base32Hex;
use Spatie\GoogleCalendar\Event;
use Seka\Terminy\Dtos\UdalostDTO;
use Seka\Terminy\Services\External\Calendar\CalendarService;

/**
 *
 */
final class GoogleCalendarService implements CalendarService
{
    /**
     *
     */
    private const ID_PREFIX = 'google-cal-portal-terminy-id';

    /**
     * @param \Seka\Terminy\Dtos\UdalostDTO $udalost
     */
    public function createEvent(UdalostDTO $udalost): void
    {
        $googleCalEvent = new Event();
        $googleCalEvent = $this->fillGoogleCalEvent($googleCalEvent, $udalost);

        $googleCalEvent->save('insertEvent');
    }

    /**
     * @param \Seka\Terminy\Dtos\UdalostDTO $udalost
     */
    public function updateEvent(UdalostDTO $udalost): void
    {
        $googleCalEvent = Event::find($this->hashId($udalost->id));
        $googleCalEvent = $this->fillGoogleCalEvent($googleCalEvent, $udalost);

        $googleCalEvent->save('updateEvent');
    }

    /**
     * @param \Seka\Terminy\Dtos\UdalostDTO $udalost
     */
    public function deleteEvent(UdalostDTO $udalost): void
    {
        $googleCalEvent = Event::find($this->hashId($udalost->id));

        $googleCalEvent->delete();
    }

    /**
     * @param int $udalostId
     *
     * @return string
     */
    private function hashId(int $udalostId): string
    {
        return strtolower(
            Base32Hex::encode(
                sprintf('%s-%d', self::ID_PREFIX, $udalostId)
            )
        );
    }

    /**
     * @param \Spatie\GoogleCalendar\Event  $event
     * @param \Seka\Terminy\Dtos\UdalostDTO $udalost
     *
     * @return \Spatie\GoogleCalendar\Event
     */
    private function fillGoogleCalEvent(Event $event, UdalostDTO $udalost): Event
    {
        $event->id = $this->hashId($udalost->id);
        $event->name = sprintf('%s [%s]', $udalost->nazov, $udalost->stav->label);
        $event->startDateTime = $udalost->datum_od;
        $event->endDateTime = $udalost->datum_do;
        $event->location = $udalost->miesto_konania->adresa;
        $event->description = $this->fillDescription($udalost);

        return $event;
    }

    /**
     * @param \Seka\Terminy\Dtos\UdalostDTO $udalost
     *
     * @return string
     */
    private function fillDescription(UdalostDTO $udalost): string
    {
        return "<p>Druh udalosti: {$udalost->druh->label}<br>Stav: {$udalost->stav->label}<br>Kapacita: {$udalost->kapacita}<br>Registrácia: {$udalost->registracia->label}</p><hr>{$udalost->popis}";
    }
}
