<?php

namespace Velis\Mail\Protocol;

use Velis\App;

class ImapOAuth2 extends \Zend\Mail\Protocol\Imap
{
    private XOauth2Auth $xoauth2Auth;

    private string $clientId;
    private string $clientSecret;

    public function __construct($host = '', $port = null, $ssl = false, $clientId = '', $clientSecret = '')
    {
        $this->xoauth2Auth = new XOauth2Auth(App::$di->get('msTokenService'));
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;

        parent::__construct($host, $port, $ssl);
    }


    /**
     * Login to IMAP server.
     *
     * @param  string $user      username
     * @param  string $password  password
     * @return bool success
     */
    public function login($user, $password)
    {
        $tokenString = $this->xoauth2Auth->encodeXoauth2Sasl($user, $this->clientId, $this->clientSecret);
        return $this->requestAndResponse('AUTHENTICATE XOAUTH2', [$tokenString], true);
    }
}
