<?php

namespace Benhauer\Salesmanago\Model\Config\Source;

use \Magento\Framework\Message\ManagerInterface;

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

use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;

class Select implements \Magento\Framework\Option\ArrayInterface
{
    public $factoryOrganizer;
    public $model;
    public $request;

    public function __construct(
        FactoryOrganizer $factoryOrganizer,
        UserModel $model,
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->factoryOrganizer = $factoryOrganizer;
        $this->model = $model;
        $this->request = $request;
    }

    /**
     * @return array
     */
    public function toOptionArray()
    {
        return $this->getOwnersEmailsList();
    }

    /**
     * @return array - owners emails list for config select;
    */
    public function getOwnersEmailsList()
    {
        $answer = [];

        try {
            $this->storeResolver();

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

            if ($response['success'] && isset($response['users'])) {
                foreach ($response['users'] as $user) {
                    $answer[] = ['value' => $user, 'label' => $user];
                }
                return $answer;
            }

            return $answer;
        } catch (\Exception $e) {
            return $answer;
        }
    }

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

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

        return $this;
    }
}
