<?php

require_once('DBLayer.php');

class ModulesUpdater extends DBLayer
{

    public function __construct()
    {
        parent::__construct('module', 'modules', 'id');
    }

    public function update($blocksInfo)
    {
        if (empty($blocksInfo)) return;

        // update modules table - alignment of the order list
        foreach($blocksInfo as $position => $blocks) {
            $this->_normalizeBlocksByPosition($position);
            $orders = $this->_getOrdersSelectedBlocks($blocks);
            foreach($blocks as $order => $id) {
                $row = $this->fetch($id);
                $row->position = $position;
                $row->ordering = $orders[$order];
                $this->save($row);
            }
        }
    }

    private function _getOrdersSelectedBlocks($blocks) {
        $ids = array();
        foreach ($blocks as $key => $value) {
            $ids[] = 'id = ' . $value;
        }
        $query = 'SELECT * FROM #__' . $this->_table . ' WHERE ' . implode(' or ', $ids) . ' order by ordering';
        $this->_db->setQuery($query);
        $rows = $this->_db->loadAssocList();
        $orders = array();
        for ($i = 0; $i < count($rows); $i++) {
            $orders[] = $rows[$i]['ordering'];
        }
        return $orders;
    }

    private function _normalizeBlocksByPosition($position)
    {
        $query = 'SELECT * FROM #__' . $this->_table . ' WHERE position = "' . $position . '" order by ordering';
        $this->_db->setQuery($query);
        $rows = $this->_db->loadAssocList();
        if ($this->_db->getErrorNum())
            exit("error:" . $this->_db->stderr());
        $result = array();
        for ($i = 0; $i < count($rows); $i++) {
            $result[$i] = JTable::getInstance($this->_entity);
            $result[$i]->load($rows[$i]['id']);
            if ($i > 0) {
                $currentOrder = $result[$i]->ordering;
                $prevOrder = $result[$i - 1]->ordering;
                if ($currentOrder == $prevOrder || $currentOrder < $prevOrder)
                    $result[$i]->ordering = $prevOrder + 1;
            }
            $this->save($result[$i]);
        }
    }

}