<?php defined('SYSPATH') or die('No direct access allowed.');
/**
 * @package    Netlist
 * @author     K Anderson <bitbashing@gmail.com>
 * @author     Darren Schreiber <d@d-man.org>
 * @license    Mozilla Public License (MPL)
 */
class NetListManager_Controller extends Bluebox_Controller
{
    protected $baseModel = 'NetList';

    public function __construct()
    {
        parent::__construct();

        stylesheet::add('netlist', 40);
    }

    public function index()
    {
        $this->template->content = new View('generic/grid');

        // Setup the base grid object
        $grid = jgrid::grid($this->baseModel, array(
                'caption' => 'Network Lists'
            )
        );

        // Add the base model columns to the grid
        $grid->add('net_list_id', 'ID', array(
                'hidden' => true,
                'key' => true
            )
        );
        $grid->add('name', 'Name');

        // Add the actions to the grid
        $grid->addAction('netlistmanager/edit', 'Edit', array(
                'arguments' => 'net_list_id'
            )
        );
        $grid->addAction('netlistmanager/delete', 'Delete', array(
                'arguments' => 'net_list_id'
            )
        );
        
        // Let plugins populate the grid as well
        $this->grid = $grid;
        plugins::views($this);

        // Produce a grid in the view
        $this->view->grid = $this->grid->produce();
    }

    protected function loadBaseModel($id = NULL, $baseModel = NULL)
    {
        parent::loadBaseModel($id, $baseModel);

        if (!empty($this->netlist['system_list']) AND $this->netlist['system_list'] != 'trunks.auto')
        {
            message::set($this->netlist['name'] . ' is generated by FreeSwitch and can not be edited!', 'alert');

            $this->returnQtipAjaxForm(NULL);

            url::redirect(Router::$controller);
        }
    }

    protected function prepareUpdateView()
    {
        $allowList = empty($_POST['ips']['allow']) ? array() : array_flip($_POST['ips']['allow']);

        $denyList = empty($_POST['ips']['deny']) ? array() : array_flip($_POST['ips']['deny']);

        $options = array(
            '127.0.0.1/32' => '127.0.0.1 (Loopback)',
            '10.0.0.0/8' => '10.0.0.0 - 10.255.255.255 (Private Network)',
            '172.16.0.0/12' => '172.16.0.0 - 172.31.255.255 (Private Network)',
            '192.168.0.0/16' => '192.168.0.0 - 192.168.255.255 (Private Network)'
        );

        $allListItems = Doctrine::getTable('NetListItem')->findAll();

        foreach ($allListItems as $item)
        {
            $cidr = $item['record'];

            $range = network::cidr2range($cidr);

            if (empty($range))
            {
                $description = $cidr;
            }
            else if ($range['start'] == $range['end'])
            {
                $description = $range['start'];
            }
            else
            {
                $description = $range['start'] . ' - ' . $range['end'];
            }

            if (!empty($item['description']))
            {
                $description .= ' (' . $item['description'] . ')';
            }

            // all net lists go into the options list
            $options[$cidr] = $description;

            // check if it is in the selected list
            if ($this->netlist['net_list_id'] == $item['net_list_id'])
            {
                if (empty($item['allow']))
                {
                    $denyList[$cidr] = $description;
                } 
                else
                {
                    $allowList[$cidr] = $description;
                }
            }
        }

        $this->view->netListItems = array_unique($options);

        $this->view->netListAllow = array_keys($allowList);

        $this->view->netListDeny = array_keys($denyList);

        parent::prepareUpdateView();
    }

    protected function save_prepare(&$object)
    {
        // get a unique list of networks
        $netListItems = $this->input->post('ips', array());

        if (!empty($netListItems))
        {
            $netListItems += array(
                'allow' => array(),
                'deny' => array()
            );

            // make each value a subarray with record and allow keys
            array_walk($netListItems['allow'], create_function('&$v,$k', '$v = array("record" => $v, "allow" => TRUE);'));

            array_walk($netListItems['deny'], create_function('&$v,$k', '$v = array("record" => $v, "allow" => FALSE);'));

            $netListItems = array_merge($netListItems['allow'], $netListItems['deny']);
        }

        $netListItems = array('NetListItem' => $netListItems);

        // incorporate the array into the the netlist
        $this->netlist->markModified('name');

        $this->netlist->synchronizeWithArray($netListItems);

        parent::save_prepare($object);
    }
}
