<?php
namespace Mtc\Cms\Handlers;

use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;

/**
 * Pages setup handler class responsible for handling the different pages setups
 * @author Rihards Silins
 * @copyright MTC Media Ltd
 * @version 1 16/02/2017
 */
class PagesSetupHandler
{
    /**
     * List available pages setups
     * @param Object TwigLoader $twig_loader
     * @return string[] $pages_setups_list
     */
    public static function listPagesSetups($twig_loader)
    {
        $result = array();
        $theme_directories = array();

        foreach ($twig_loader->getPaths() as $extend_path) {
            $theme_path = $extend_path . '/../pages_setups/';
            if (is_dir($theme_path)) {
                $theme_directories[] = $extend_path . '/../pages_setups/';
            }
        }

        foreach ($theme_directories as $filesystem_template_path) {

            foreach (
                $iterator = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator(
                        $filesystem_template_path,
                        RecursiveDirectoryIterator::SKIP_DOTS
                    ),
                    RecursiveIteratorIterator::SELF_FIRST
                ) as $item
            ) {
                $filename = $iterator->getSubPathName();
                $name = $filename;
                $setup = file_get_contents($filesystem_template_path . "/" . $filename);
                $setup_as_array = json_decode($setup, true);
                if (!empty($setup_as_array['title'])) {
                    $name = $setup_as_array['title'];
                }

                $setup = array(
                    'filename'      => $filename,
                    'setup'         => json_encode($setup_as_array['logic']['pages'], JSON_PRETTY_PRINT),
                    'name'          => $name,
                    'priority'      => $priority
                );

                $priority = 2;
                if (isset($setup_as_array['priority'])) {
                    $priority = $setup_as_array['priority'];
                }

                if (isset($result[$priority])) {
                    $result[] = $setup;
                } else {
                    $result[$priority] = $setup;
                }
            }

        }

        asort($result);
        return $result;
    }
}
