<?php
/**
 * $Horde: nag/data.php,v 1.23 2003/06/17 23:27:54 slusarz Exp $
 *
 * Copyright 2001-2003 Jan Schneider <jan@horde.org>
 *
 * See the enclosed file COPYING for license information (GPL).  If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 */

function _cleanup()
{
    global $import_step;
    $import_step = 1;
    return IMPORT_FILE;
}

define('NAG_BASE', dirname(__FILE__));
require_once NAG_BASE . '/lib/base.php';
require_once HORDE_BASE . '/lib/Data.php';

if (!$conf['menu']['import_export']) {
    header('Location: ' . Horde::applicationUrl('index.php', true));
    exit;
}

/* Allow preferred theme to override settings. */
Horde::getThemeConfig(NAG_BASE);

/* Importable file types. */
$file_types = array('csv' => _("CSV"));

/* Templates for the different import steps. */
$templates = array(
    IMPORT_FILE => array(NAG_TEMPLATES . '/data/import.inc', NAG_TEMPLATES . '/data/export.inc'),
    IMPORT_CSV => array($registry->getParam('templates', 'horde') . '/data/csvinfo.inc'),
    IMPORT_MAPPED => array($registry->getParam('templates', 'horde') . '/data/csvmap.inc'),
    IMPORT_DATETIME => array($registry->getParam('templates', 'horde') . '/data/datemap.inc')
);

/* Field/clear name mapping. */
$app_fields = array('name'      => _("Name"),
                    'desc'      => _("Description"),
                    'category'  => _("Category"),
                    'due'       => _("Due By"),
                    'priority'  => _("Priority"),
                    'completed' => _("Completion Status"),
                    'flags'     => _("Flags"));

/* Date/time fields. */
$time_fields = array('due' => 'datetime');

/* Initial values. */
$param = array('time_fields' => $time_fields,
               'file_types'  => $file_types);
$import_format = Horde::getFormData('import_format', '');
$import_step   = Horde::getFormData('import_step', 0) + 1;
$actionID      = Horde::getFormData('actionID');
$error         = false;

/* Loop through the action handlers. */
switch ($actionID) {
case 'export':
    $exportID = Horde::getFormData('exportID');

    /* Create a Nag storage instance. */
    require_once NAG_BASE . '/lib/Driver.php';
    $storage = &Nag_Driver::factory($conf['storage']['driver'], Auth::getAuth(),
                                    $conf['storage']['params']);
    $storage->retrieve();

    /* Get the full, sorted task list. */
    $tasks = Nag::listTasks($prefs->getValue('sortby'), $prefs->getValue('sortdir'));

    switch ($exportID) {
    case EXPORT_CSV:
        if (count($tasks) == 0) {
            $notification->push(_("There were no tasks to export."), 'horde.message');
            $error = true;
        } else {
            $data = array();
            foreach ($tasks as $task) {
                unset($task['task_id']);
                $task['desc'] = str_replace(',', '', $task['desc']);
                $data[] = $task;
            }
            $csv = &Horde_Data::singleton('csv');
            $csv->exportFile(_("tasks.csv"), $data, true);
            exit;
        }
    }
    break;

case IMPORT_FILE:
    $_SESSION['import_data']['target'] = Horde::getFormData('tasklist_target');
    break;
}

if (!$error) {
    $data = &Horde_Data::singleton($import_format);
    if (is_a($data, 'PEAR_Error')) {
        $notification->push(_("This file format is not supported."), 'horde.error');
        $next_step = IMPORT_FILE;
    } else {
        $next_step = $data->nextStep($actionID, $param);
        if (is_a($next_step, 'PEAR_Error')) {
            $notification->push($next_step->getMessage(), 'horde.error');
            $next_step = $data->cleanup();
        }
    }
}

/* We have a final result set. */
if (is_array($next_step)) {
    /* Create a Nag storage instance. */
    require_once NAG_BASE . '/lib/Driver.php';
    $storage = &Nag_Driver::factory($conf['storage']['driver'], $_SESSION['import_data']['target'],
                                    $conf['storage']['params']);
    $storage->retrieve();
    foreach ($next_step as $row) {
        foreach ($app_fields as $field => $null) {
            if (!array_key_exists($field, $row)) {
                $row[$field] = '';
            }
        }
        $task_id = $storage->addTask($row['name'], $row['desc'], $row['due'],
                                     $row['priority'], $row['completed'],
                                     $row['category']);
        if (!empty($row['flags'])) {
            $storage->setFlag($task_id, $row['flags'], true);
        }
    }
    $success = $storage->store();
    if (is_a($success, 'PEAR_Error')) {
        $notification->push(sprintf(_("There was an error importing the data: %s"),
                                    $success->getMessage()), 'horde.error');
    } else {
        $notification->push(sprintf(_("%s file successfully imported"),
                                    $file_types[$_SESSION['import_data']['format']]), 'horde.success');
    }
    $next_step = $data->cleanup();
}

$title = _("Import/Export Tasks");
$js_onLoad = null;
require NAG_TEMPLATES . '/common-header.inc';
Nag::menu();

foreach ($templates[$next_step] as $template) {
    require $template;
}

require NAG_TEMPLATES . '/common-footer.inc';
