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

class Plugg_System_Admin_ListPlugins extends Sabai_Application_ModelEntityController_List
{
    private $_sortBy = array('priority', 'DESC');
    private $_select;

    public function __construct()
    {
        parent::__construct('Plugin', array('properties' => array('name', 'version', 'active', 'priority')));
    }

    protected function _onListEntities($entities, Sabai_Application_Context $context)
    {
        $installed = array();
        $local = $installable = $this->pluginManager->getLocalPlugins($context->request->getAsBool('refresh'));
        foreach ($entities as $plugin) {
            $plugin_library = $plugin->get('library');
            if (isset($local[$plugin_library])) {
                $installed[$plugin_library] = $local[$plugin_library];
                unset($installable[$plugin_library]);
            }
        }
        $context->response->setVars(array(
            'requested_select' => $this->_select,
            'requested_sortby' => implode(',', $this->_sortBy),
            'local_plugins'    => $local,
            'installed_plugins' => $installed,
            'installable_plugins' => $installable,
            'plugins_dependency' => $this->pluginManager->getPluginsDependency()
        ));
        return $entities;
    }

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

    protected function _getRequestedSort(Sabai_Request $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] == 'priority') {
            return 'priority';
        }
        return array($this->_sortBy[0], 'priority');
    }

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

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