<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Sibs\Sibs\Model\Config\Source;

use Exception;
use Magento\Framework\Option\ArrayInterface;
use Sibs\Sibs\Utils\SibsLog;

class Environment implements ArrayInterface
{
    const DEV_OPTION = 'DEV';

    const TST_OPTION = 'TST';

    const CER_OPTION = 'CER';

    const LIVE_OPTION = 'LIVE';

    /**
     * @var string[]
     */
    protected $_env_array;

    /**
     * @var string[]
     */
    protected $_environment = [
        self::DEV_OPTION  => 'DEV',
        self::TST_OPTION  => 'TST',
        self::CER_OPTION  => 'CER',
        self::LIVE_OPTION => 'LIVE',
    ];

    public function __construct()
    {
        $file             = json_decode(file_get_contents(BP . '/app/code/Sibs/Sibs/environment.json'), true);
        $this->_env_array = $file['environment'];
    }

    /**
     * @return array
     */
    public function toOptionArray()
    {
        $options = [];

        foreach ($this->_environment as $code => $label) {
            if ($this->validateEnvironment($code)) {
                $options[] = [
                    'value' => $code,
                    'label' => __($label),
                ];
            }
        }

        return $options;
    }

    private function validateEnvironment($env)
    {
        try {
            return in_array($env, $this->_env_array);
        } catch (Exception $e) {
            SibsLog::info('Caught exception on accessing environment json: ' . $e->getMessage());

            return false;
        }
    }
}
