<?php

@define('NAG_BASE', dirname(__FILE__));
require_once NAG_BASE . '/lib/base.php';
require_once 'Horde/Xml/Element.php';
require_once 'Horde/Xml/Element/Exception.php';
require_once 'Horde/Form.php';
require_once 'Horde/Variables.php';

$vars = Variables::getDefaultVariables();
$form = new Horde_Form($vars, 'Import Mindmap', 'mindmap');
$tasklists = array();
foreach (Nag::listTasklists(false, PERMS_EDIT) as $id => $tl) {
    $tasklists[$id] = $tl->get('name');
}
$form->addVariable(_("Tasklist to import to"), 'tasklist', 'enum', true, false, null, array($tasklists));
$form->addVariable(_("Select file"), 'mindmap_file', 'file', true);
$v = $form->addVariable(_("Skip the first mindmap node (treat it as the tasklist root)?"), 'skip_root', 'boolean', false);
$v->setDefault(true);

if ($form->validate()) {
    $form->getInfo($vars, $info);
    // @TODO PERMISSIONS!
    $storage = Nag_Driver::factory($info['tasklist']);

    $e = new Horde_Xml_Element(file_get_contents($info['mindmap_file']['file']));
    $first = $e->node;
    if ($info['skip_root']) {
        foreach ($first->node as $node) {
            recurse($node);
        }
    } else {
        recurse($first);
    }

    header('Location: list.php');
    exit;
}

$title = 'Import Mindmap';
require NAG_TEMPLATES . '/common-header.inc';
require NAG_TEMPLATES . '/menu.inc';
$form->renderActive(null, null, '', 'post');
require $registry->get('templates', 'horde') . '/common-footer.inc';

function recurse($node, $parent = '') {
    global $storage;
    $result = $storage->add($node['TEXT'], '', null, null, null, null, null, null, null, null, $parent, null, Auth::getAuth(), null);
    if (is_a($result, 'PEAR_Error')) {
        Horde::fatal($result, __FILE__, __LINE__);
    }
    $parentId = $result[0];
    if ($node->node) {
        foreach ($node->node as $child) {
            recurse($child, $parentId);
        }
    }
}