<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Source\Provider\GoogleCalendar;

use function YOOtheme\app;
use YOOtheme\Event;
use ZOOlanders\YOOessentials\Api\Google\GoogleCalendarApiInterface;
use ZOOlanders\YOOessentials\Auth\AuthManager;
use ZOOlanders\YOOessentials\Auth\AuthOAuth;
use ZOOlanders\YOOessentials\Source\Type\AbstractSourceType;
use ZOOlanders\YOOessentials\Source\Type\SourceInterface;

class GoogleCalendarSource extends AbstractSourceType implements SourceInterface
{
    private ?GoogleCalendarApiInterface $api = null;

    public function types(): array
    {
        return [
            new Type\GoogleCalendarCalendarType(),
            new Type\GoogleCalendarEventType(),
            new Type\GoogleCalendarProfileType(),
            new Type\GoogleCalendarAttendeeType(),
            new Type\GoogleCalendarAttachmentType(),
            new Type\GoogleCalendarEventQueryType($this),
            new Type\GoogleCalendarEventsQueryType($this),
            new Type\GoogleCalendarCalendarQueryType($this),
        ];
    }

    public function auth(): ?AuthOAuth
    {
        $account = $this->config()['account'] ?? null;

        if (!$account) {
            throw new \Exception('Auth Account must be specified.');
        }

        return app(AuthManager::class)->auth($account);
    }

    public function api(): GoogleCalendarApiInterface
    {
        if ($this->api) {
            return $this->api;
        }

        $this->api = app(GoogleCalendarApiInterface::class);

        try {
            $this->api->withToken($this->auth()->accessToken());
        } catch (\Exception $e) {
            Event::emit('yooessentials.error', [
                'addon' => 'source',
                'provider' => 'google-calendar',
                'error' => $e->getMessage(),
            ]);
        }

        return $this->api;
    }
}
