<?php
namespace IntellexApps\PHP\UploadFile\Domain\Service;

use IntellexApps\PHP\UploadFile\Util\Configuration;
use IntellexApps\PHP\UploadFile\Util\Inflector;

class ConfigurationService extends BaseService
{

    const CONFIGURATION_DIR = '.config';
    const META_DIR = '.meta';

    /** @var string */
    var $configDirectory;

    /** @var FileSystemService */
    var $fileSystemService;

    /** @var UploadFileService */
    var $uploadFileService;

    /**
     * Initialize service
     */
    public function init()
    {
        $this->fileSystemService = $this->get('file_system');
        $this->uploadFileService = $this->get('upload');
    }

    /**
     * Get config directory
     *
     * @param null $subPath
     * @return string
     */
    public function getConfigDirectory($subPath = null)
    {
        $dirName = self::CONFIGURATION_DIR;

        if($subPath) {
            $dirName = Inflector::joinPaths([
                FileSystemService::relativePath($subPath),
                $dirName
            ]);
        }

        $fullPath = $this->uploadFileService->getFullPath($dirName);

        // TODO: Use file_system service for this
        if(!is_dir($fullPath)) {
            mkdir($fullPath, 0777, true);
        }

        return $fullPath;
    }

    /**
     * Initialize configuration
     */
    public function initializeConfiguration()
    {

        $loadConfigId = null;

        /**
         * Check for dossier_id and session_id in $_GET
         *
         * TODO: Extract these in controller and pass them here if possible
         */
        if(isset($_GET['dossier_id'])) {
            // Set session id
            if(isset($_GET['session_id'])) {
                session_id($_GET['session_id']);
            }

            // Start session
            session_start();

            if(isset($_SESSION['dossier'][$_GET['dossier_id']])) {
                $loadConfigId = $_GET['dossier_id'];
                Configuration::load($_SESSION['dossier'][$loadConfigId]);
            }
        }

        /**
         * If session is not started - start it
         */
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }

        /**
         * Load last saved config
         */
        if(isset($_SESSION['dossier']['last_loaded_config'])) {
            $loadConfigId = 'last_loaded_config';
            Configuration::load($_SESSION['dossier'][$loadConfigId]);
        }

        if($loadConfigId) {
            $this->container->get('hook')->loadHooks(Configuration::$hooks);
        }

        // TODO: Store current configuration and compare - if differences - reinitialize
        $configDirectory = $this->getConfigDirectory();

        if(!$this->fileSystemService->directoryExists($configDirectory)) {
            $this->fileSystemService->createDirectory($configDirectory);
        }

        $this->initializeRoles();

        $this->initializeTrash();
    }

    /**
     * Initialize roles
     */
    private function initializeRoles()
    {
        $this->fileSystemService->writeFile(
            $this->getConfigDirectory() . DS . 'roles.data',
            serialize($this->get('permission')->buildRoles()),
            true
        );
    }

    /**
     * Initialize trash
     */
    private function initializeTrash()
    {
        $trashPath = $this->uploadFileService->getTrashLocation();
        if(!$this->fileSystemService->directoryExists($trashPath)) {
            $this->fileSystemService->createDirectory($trashPath);
        }
    }

    /**
     * Get roles
     *
     * @return mixed
     */
    public function getRoles()
    {
        return unserialize(file_get_contents($this->getConfigDirectory() . DS . 'roles.data'));
    }
}