<?php
class theme
{
    const DIRECTORY = 'extend/theme/';
    
    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
    
    public static function get($id)
    {
        if (!preg_match('/^[a-z0-9]+$/i', $id))
        {
            throw new exception('Theme id is not valid.');
        }
        
        $directory = self::DIRECTORY . $id . '/';
        
        if (!is_dir($directory))
        {
            throw new exception('Theme does not exist.');
        }
        
        $file = $directory . 'config.json';
        
        if (!is_file($file))
        {
            throw new exception('Theme config file is missing.');
        }
        
        $config = json_decode(file_get_contents($file), true);
        
        if (!self::validate($config))
        {
            throw new exception('Theme config is not valid.');
        }
        
        $theme['id'] = $id;
        $theme += $config;
        $options = array();
        
        foreach ($theme['skin']['options'] as $name => $option)
        {
            $options[$name] = array(
                'name' => $name,
                'selector' => $option[0],
                'property' => $option[1],
                'type' => $option[2],
                'value' => $option[3],
                'parameters' => isset($option[4]) ? (array) $option[4] : array()
            );
        }
        
        $theme['skin']['options'] = $options;
        return $theme;
    }
    
    public static function get_current()
    {
        $setting = setting::get('id', 'site.theme');
        $theme = self::get($setting['value']);
        
        foreach (setting::get_list('site.theme') as $setting)
        {
            if ($setting['name'] !== 'id')
            {
                $theme['skin']['options'][$setting['name']]['value'] = $setting['value'];
            }
        }
        
        return $theme;
    }
    
    public static function get_list()
    {
        $themes = array();
        
        foreach (glob(self::DIRECTORY . '*', GLOB_ONLYDIR) as $directory) {
            $id = basename($directory);
            $themes[$id] = self::get($id);
        }
        
        return $themes;
    }
    
    protected static function validate($config)
    {
        return true;
    }
}
