<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Arr;
use Carbon\Carbon;

use Google_Client;
use Google_Service_Calendar;
use App\Utilities\CalendarEvent;

class GoogleCalendar extends Model
{
    use HasFactory;

    public function saveGoogleCalendar(array $input, $id = null)
    {
        if ($id >= 1) {
            $google_calendar = GoogleCalendar::findOrFail($id);
        } else {
            $google_calendar = new GoogleCalendar();
        }

        $google_calendar->calendar_id = Arr::get($input, 'calendar_id');
        $google_calendar->google_id = Arr::get($input, 'google_id');
        $google_calendar->name = Arr::get($input, 'name');
        $google_calendar->color = Arr::get($input, 'color');
        $google_calendar->filter = Arr::get($input, 'filter');
        $google_calendar->save();

        cache()->tags([cache_name($google_calendar)])->flush();
        return $google_calendar;
    }

    public function calendar()
    {
        return $this->belongsTo(Calendar::class);
    }

    public function getCalendarEvents($input = null)
    {
        $cache_id = preg_replace("/[^A-Za-z0-9 ]/", '', $this->google_id);

        if (!$this->google_id) {
            return collect();
        }

        $start_date = now();
        $end_date = null;

        if (Arr::get($input, 'start_date')) {
            $start_date = Carbon::parse(Arr::get($input, 'start_date'));
        }

        if (Arr::get($input, 'end_date')) {
            $end_date = Carbon::parse(Arr::get($input, 'end_date'));
        }

        return cache()->tags([cache_name($this->calendar?->contentElement)])->remember('google-calendar-'.$cache_id.'-'.str_replace('#', '', $this->color).'-events-'.$start_date->format('Y-m-d').'-'.$end_date?->format('Y-m-d'), 1800, function () use ($start_date, $end_date) {
            $client = new Google_Client();
            $client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
            $client->setAuthConfig(base_path('sa/calendar.json'));
            $client->setSubject('sa_developer@brentwood.ca');

            $service = new Google_Service_Calendar($client);

            // https://developers.google.com/calendar/v3/reference/events/list

            $optParams = [
              //'maxResults' => 10, // the default is 250
              'orderBy' => 'startTime',
              'singleEvents' => true,
              'timeMin' => $start_date->toRfc3339String(),
            ];

            if ($end_date) {
                $optParams['timeMax'] = $end_date->toRfc3339String();
            }

            $results = $service->events->listEvents($this->google_id, $optParams);
            $events = CalendarEvent::convertGoogleCalendarEvents(collect($results->getItems()), $this->color, $this->filter);

            return $events;
        });
    }
}
