<?php
/**
 * @copyright: Copyright © 2023 Firebear Studio. All rights reserved.
 * @author   : Firebear Studio <fbeardev@gmail.com>
 */

namespace Firebear\ImportExport\Controller\Dropbox;

use Exception;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Cache\TypeListInterface as CacheTypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Storage\WriterInterface as StorageWriterInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\LocalizedException;
use Firebear\ImportExport\Model\Source\Type\Dropbox;

/**
 * Controller SigninCallback
 */
class SigninCallback extends Action
{
    public const CONFIG_PATH_REFRESH_TOKEN = 'firebear_importexport/dropbox/refresh_token';

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var CacheTypeListInterface
     */
    protected $cacheTypeList;

    /**
     * @var StorageWriterInterface
     */
    protected $storageWriterInterface;

    /**
     * @var Dropbox
     */
    protected $dropbox;

    /**
     * SigninCallback constructor.
     * @param Context $context
     * @param ScopeConfigInterface $scopeConfig
     * @param CacheTypeListInterface $cacheTypeList
     * @param StorageWriterInterface $storageWriterInterface
     * @param Dropbox $dropbox
     */
    public function __construct(
        Context $context,
        ScopeConfigInterface $scopeConfig,
        CacheTypeListInterface $cacheTypeList,
        StorageWriterInterface $storageWriterInterface,
        Dropbox $dropbox
    ) {
        parent::__construct($context);
        $this->scopeConfig = $scopeConfig;
        $this->cacheTypeList = $cacheTypeList;
        $this->storageWriterInterface = $storageWriterInterface;
        $this->dropbox = $dropbox;
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|\Magento\Framework\View\Result\Layout
     */
    public function execute()
    {
        try {
            if ($this->getRequest()->getParam('error')) {
                throw new LocalizedException(__($this->getRequest()->getParam('error_description')));
            }

            $code = $this->getRequest()->getParam('code');
            $result = [];
            if (!empty($code)) {
                $result = $this->dropbox->getRefreshTockenByAuthorizationCode($code);
            }
            if (empty($result['error'])) {
                $refreshToken = $result['refresh_token'] ?? '';
                if (!empty($refreshToken)) {
                    $this->saveRefreshToken($refreshToken);
                    $message = __('Success! We have made changes to the module settings.');
                } else {
                    $message = __('Error! Refresh token is empty.');
                }
            } else {
                $message = $result['error'];
            }
        } catch (Exception $e) {
            $message = __('Error! Message: %1', $e->getMessage());
        }

        $result = $this->resultFactory->create(ResultFactory::TYPE_RAW);

        $content = '<p><b> ' . $message .'</b></p>
        <button onclick="closeAndRefreshParent()">Close window and refresh configs</button>
        <script>
            function closeAndRefreshParent() {
                window.opener.location.reload();
                window.close();
            }
        </script>';

        $result->setHeader('Content-Type', 'text/html');
        $result->setContents($content);
        return $result;
    }

    /**
     * Save RefreshToken
     *
     * @param string $refreshToken
     */
    public function saveRefreshToken($refreshToken)
    {
        $this->storageWriterInterface->save(static::CONFIG_PATH_REFRESH_TOKEN, $refreshToken);
        $this->clearConfigCache();
    }

    /**
     * Clear ConfigCache
     */
    public function clearConfigCache()
    {
        $this->cacheTypeList
            ->cleanType(\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER);
    }
}
