<?php namespace NicoSt\GCalendar\FormWidgets;

use Backend\Classes\FormWidgetBase;
use Log;
use Flash;
use Lang;
use Redirect;

use NicoSt\GCalendar\Models\Settings;
use NicoSt\GCalendar\Classes\GoogleCalendarClient;

class OAuth extends FormWidgetBase {

    protected $defaultAlias = 'googleOAuth';

    public function render() {

        $class = new GoogleCalendarClient(true);
        $client = $class->getClient();

        $this->vars['redirectUrl'] = $client->getRedirectUri();
        $this->vars['isAccessTokenExpired'] = $client->isAccessTokenExpired() ? '1' : '0';
        $this->vars['clientIdExist'] = null != Settings::get('client_id', null) ? '1' : '0';
        $this->vars['accessToken'] = print_r(Settings::get('access_token'), true);

        return $this->makePartial('oauth');
    }

    public function onRequestAccessToken() {

        $class = new GoogleCalendarClient(true);
        $client = $class->getClient();

        if ($client->isAccessTokenExpired()) {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            Log::info('G-Calendar: Request authorization with URL ['. $authUrl .'].');

            $this->vars['auth_url'] = $authUrl;

            return  $this->makePartial('gaccess');
        }

        Log::info('G-Calendar: Access token not expired.');
        Flash::error(Lang::get('nicost.gcalendar::lang.message.accessTokenNotExpired'));
    }

    public function onClearAccessToken() {
        Settings::set('access_token', '');
        Flash::success(Lang::get('nicost.gcalendar::lang.message.accessTokenRemoved'));

        $this->vars['isAccessTokenExpired'] = '1';

        return Redirect::refresh();
    }

}