<?php

/**
 * Description of ShortCodeManager
 *
 * @author Mohammed Osman  <osmancode@gmail.com>
 */
Yii::import('admin.modules.widgets.models.WidgetInstance');
Yii::import('admin.modules.widgets.models.Widget');

class ShortCodeManager {

    const pattern = '/\[shortcode:(\w*?):(\d*)(.*?)\]/';

    public static function parse($content) {
        $result = preg_replace_callback(self::pattern, 'self::processCode', $content);
        return $result;
    }

    private static function processCode($matches) {
        if (isset($matches[1])) {
            /**
             * Assign parsed Data
             */
            $shortcode = isset($matches[1]) ? $matches[1] : false;
            $widgetInstanceID = isset($matches[2]) ? $matches[2] : false;
            $inlineOptions = (isset($matches[3]) && strlen($matches[3]) > 1) ? $matches[3] : false;
            if ($widgetInstanceID) {
                // load widget instance.
                $widgetInstance = WidgetInstance::model()->findByPk($widgetInstanceID * 1);

                if ($widgetInstance !== NULL) {
                    if ($result = parse_url(html_entity_decode($inlineOptions))) {
                        $inlineOptions = array();
                        if (isset($result['query'])) {
                            parse_str($result['query'], $inlineOptions);
                        }
                        if (is_array($inlineOptions)) {

                            $options = array_merge($widgetInstance->getOptions(), $inlineOptions);

                            if (class_exists($widgetInstance->widget->class)) {
                                return Yii::app()->getController()->widget($widgetInstance->widget->class, array('options' => $options), true);
                            } else {
                                return '<!--CLASS NOT EXISTS-->';
                            }
                        } else {
                            return '<!--INLINE OPTIONS NOT ARRAY-->';
                        }
                    } else {
                        return '<!--PARSE URL-->';
                    }
                } else {
                    return '<!--WIDGET INSTANCE EQUALS TO NULL-->';
                }
            } else {
                return '<!--SHORT CODE NOT FOUND-->';
            }
        }
        return '<!--SHORT CODE NOT FOUND-->';
    }

    public static function strip($content) {
        $result = preg_replace(self::pattern, '', $content);
        return $result;
    }

}
