<?php
require_once 'Sabai/Application/ModelEntityController/Paginate.php';

class Plugg_User_Admin_Widget_List extends Sabai_Application_ModelEntityController_Paginate
{
    var $_select;
    var $_sortBy = array('order', 'ASC');

    function __construct()
    {
        $options = array(
            'tplVarPages' => 'widget_pages',
            'tplVarPageRequested' => 'widget_page_requested',
            'tplVarEntities' => 'widgets',
            'perpage' => 30
        );
        parent::__construct('Widget', $options);
    }

    function _getCriteria(Sabai_Application_Context $context)
    {
        $this->_select = $context->request->getAsStr('select');
        switch($this->_select) {
            case 'active':
                $criteria = Sabai_Model_Criteria::createValue('widget_active', 1);
                break;
            case 'inactive':
                $criteria = Sabai_Model_Criteria::createValue('widget_active', 0);
                break;
            case 'mini':
                $criteria = Sabai_Model_Criteria::createValue('widget_mini', 1);
                break;
            default:
                $this->_select = 'all';
                $criteria = false;
                break;
        }
        return $criteria;
    }

    function _getRequestedSort($request)
    {
        if ($sort_by = $request->getAsStr('sortby')) {
            $sort_by = explode(',', $sort_by);
            if (count($sort_by) == 2) {
                $this->_sortBy = $sort_by;
            }
        }
        if ($this->_sortBy[0] == 'order') {
            return 'order';
        }
        return array($this->_sortBy[0], 'order');
    }

    function _getRequestedOrder($request)
    {
        if ($this->_sortBy[0] != 'order') {
            return array($this->_sortBy[1], 'ASC');
        }
        return $this->_sortBy[1];
    }

    function _onPaginateEntities($entities, Sabai_Application_Context $context)
    {
        $widget_names = array();
        foreach ($entities as $widget) {
            $plugin_name = $widget->get('plugin');
            if ($plugin = $this->pluginManager->getPlugin($plugin_name)) {
                $widget_name = $widget->get('name');
                $plugin_nicename = $plugin->getNicename();
                $widget_names[$plugin_name][$widget_name] = array(
                    'nicename' => sprintf($plugin->userWidgetGetNicename($widget_name), $plugin_nicename),
                    'plugin_nicename' => $plugin_nicename,
                    'plugin_library' => $plugin->getLibrary()
                );
            }
        }
        $context->response->setVars(array(
            'widget_names' => $widget_names,
            'widget_requested_select' => $this->_select,
            'widget_requested_sortby' => implode(',', $this->_sortBy)
        ));
        return $entities;
    }

    protected function _getModel(Sabai_Application_Context $context)
    {
        return $context->plugin->getModel();
    }
}