<?php namespace NicoSt\GCalendar\Classes;

use Log;
use Cache;

use NicoSt\GCalendar\Models\Settings;

class GoogleCalendarService {
    private $cacheTimeDefault = 15;

    private $cacheKeyCalendarList = 'GCalendar-CalendarList';
    private $cacheKeyCalendarGet = 'GCalendar-CalendarGet#';

    private $service;

    public function __construct() {
        $client = new GoogleCalendarClient(true);
        $this->service = $client->getService();
    }

    public function getCalendar($calendarId, $maxEvents = '10') {
        $cachedCalendarGet = Cache::get($this->cacheKeyCalendarGet.$calendarId);
        $cacheTime = Settings::get('cache_time', $this->cacheTimeDefault);

        if(!isset($cachedCalendarGet) || $cacheTime == 0) {
            // "timeMin"        -> Set param to only get upcoming events
            // "singleEvents"   -> Split recurring events into single events
            // "orderBy"        -> Order events by startTime
            // "maxResults"     -> Maximum number of events returned on one page
            $params = array(
                'timeMin' => date( DATE_RFC3339, time()),
                'singleEvents' => 'true',
                'orderBy' => 'startTime',
                'maxResults' => $maxEvents
            );

            try {
                Log::debug('G-Calendar: Call google with #getCalendar.');
                $response = $this->service->events->listEvents($calendarId, $params);

                Cache::put($this->cacheKeyCalendarGet.$calendarId, $response, $cacheTime);
                return $response;
            } catch (\Exception $e) {
                $json = json_decode($e->getMessage(), true);

                Log::error('G-Calendar: Exception occurred on #getCalendar => ['. print_r($json, true).']');
                return $json;
            }
        }
        return $cachedCalendarGet;
    }

    public function calendarList() {
        $cachedCalendarList = Cache::get($this->cacheKeyCalendarList);
        $cacheTime = Settings::get('cache_time', $this->cacheTimeDefault);
       
        if(!isset($cachedCalendarList) || $cacheTime == 0) {
            try {
                Log::debug('G-Calendar: Call google with #calendarList.');
                $response = $this->service->calendarList->listCalendarList()->getItems();

                Cache::put($this->cacheKeyCalendarList, $response, $cacheTime);
                return $response;
            } catch (\Exception $e) {
                $json = json_decode($e->getMessage(), true);

                Log::error('G-Calendar: Exception occurred on #calendarList => ['. print_r($json, true).']');
                return $json;
            }
        }
        return $cachedCalendarList;
    }

    /**
     * Returns a array like this:
     *
     * @param String $maxEvents - Amount of events to return
     *
     * @return  array['calendar_1']
     *                      ['event_1']
     *                      ['event_2']
     *          array['calendar_2']
     *                      ['event_1']
     *                      ['event_2']
     *          ...
     */
    public function allEventList($maxEvents) {
        $savedCalendars = array();
        $events = array();

        if (!empty(Settings::get('calendar_selector'))) {
            $savedCalendars = Settings::get('calendar_selector');
        }

        foreach($savedCalendars as $savedCalendar) {
            $calendarEvents = $this->getCalendar($savedCalendar['id'], $maxEvents);
            // Check for error to passthrough
            if (isset($calendarEvents['error'])) {
                return $calendarEvents;
            }
            array_push($events, $calendarEvents);
        }
        
        return $events;
    }
}