<?php

namespace Benhauer\Salesmanago\Model\SM;

use \Psr\Log\LoggerInterface;

use \Benhauer\Salesmanago\Exception\Exception;
use \Benhauer\Salesmanago\Exception\SalesManagoException;
use \Benhauer\Salesmanago\Exception\UserAccessException;
use \Benhauer\Salesmanago\Model\User as UserModel;

use \Magento\Framework\Model\AbstractModel as MagentoAbstractModel;
use \Magento\Framework\Registry;
use \Magento\Store\Model\StoreManagerInterface;
use \Magento\Framework\Model\Context;
use \Magento\Framework\Message\ManagerInterface;
use \Magento\Framework\App\Request\Http as HttpRequest;

use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
use \Benhauer\Salesmanago\Helper\Config as ConfigHelper;

class Rest extends MagentoAbstractModel
{
    public $factoryOrganizer;
    public $model;
    public $request;
    public $logger;

    public static $planTypes = [
        'B2B_BASIC' => 'Basic',
        'B2C_BASIC' => 'Basic',
        'B2B_COMPLETE' => 'Professional',
        'B2C_PRO' => 'Professional',
        'B2B_ADVANCED' => 'Enterprise',
        'B2C_ELITE' => 'Enterprise',
        'STORE' => 'SALESmanago AppStore',
        'STORE_FREE' => 'SALESmanago AppStore',
    ];

    public function __construct(
        Context $context,
        Registry $registry,
        UserModel $model,
        FactoryOrganizer $factoryOrganizer,
        ConfigHelper $config,
        ManagerInterface $messageManager,
        StoreManagerInterface $storeManager,
        HttpRequest $request
    ) {
        parent::__construct($context, $registry);
        $this->model = $model;
        $this->factoryOrganizer = $factoryOrganizer;
        $this->config = $config;
        $this->storeManager = $storeManager;
        $this->messageManager = $messageManager;
        $this->request = $request;
        $this->logger = $context->getLogger();
    }

    public function getAccountType()
    {
        try {
            $this->storeResolver();

            $userAccount = $this->factoryOrganizer->getInst(
                FactoryOrganizer::USER_ACCOUNT_C,
                UserProvider::initSettingsUser(
                    $this->model
                ),
                $this->model
            );

            $response = $userAccount->getAccountTypeWithContacts();

            if (!$response['success']) {
                $this
                    ->messageManager
                    ->addErrorMessage(__("Your SALESmanago token has expired, please logout and login again to refresh it."));
                $response = [];
            }

            $result = $this->parseResponseData($response);
            return $result;

        } catch (UserAccessException $e) {
            $this->logger->critical($e->getMessage());
            return [];
        } catch (SalesManagoException $e) {
            $this->logger->critical($e->getMessage());
            return [];
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
            return [];
        }
    }

    /**
     * Parse Salesmanago response data for account type requst
     * @param array $response
     * @return array
     */
    protected function parseResponseData($response)
    {
        $result = [
            "contactCount" => $response['contactCount'],
            "planType" => self::$planTypes[$response['planType']],
            "versionType" => $response['versionType']
        ];

        return $result;
    }

    public function storeResolver()
    {
        $storeId = $this->request->getParam('store');

        if ($storeId) {
            $this->model->setScopeId($storeId);
        }

        return $this;
    }
}
