<?php

namespace App\Controllers\Auth;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

use App\Libraries\MySocket\GoogleSocket\API as GoogleSocket;
use App\Services\Auth\GoogleService;
use App\Entities\UserEntity;

class GoogleController extends AuthController
{

    private ?GoogleSocket $_socket = null;
    private $_service = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
    }
    final public function getSocket()
    {
        if (!$this->_socket) {
            $this->_socket = new GoogleSocket();
        }
        return $this->_socket;
    }
    final public function getService(): GoogleService
    {
        if (!$this->_service) {
            $this->_service = new GoogleService($this->getSocket());
        }
        return $this->_service;
    }

    public function getSNSButton(): string
    {
        //구글 로그인 BUTTON용
        return anchor($this->getSocket()->createAuthUrl(), ICONS['GOOGLE'] . 'Google 로그인', ["class" => "btn-google"]);
    }

    //로그인처리
    protected function login_process(array $formDatas): UserEntity
    {
        if (!array_key_exists('access_code', $formDatas) || !$formDatas['access_code']) {
            throw new \Exception("구글 로그인 실패");
        }
        return $this->getService()->login($formDatas);
    }
}
