<?php
/**
 * CodeIgniter library
 *
 * @category CodeIgniter
 * @license /_licenses/untermStrich/agb_normal.pdf
 * @author Christian Koller
 * @copyright 2009 untermStrich
 * @package us_libraries
 * @version $Id: opentasks_dav_values.php christian $
*/

if (!defined('BASEPATH')) { exit('No direct script access allowed'); }

require_once APPPATH.'us_libraries/value_objects/opentasks_values.php';

/**
 * Used to save a opentasks via DAV
 *
 * @property    My_Controller           $CI                     The main CI object
 */
class Opentasks_dav_values extends Opentasks_values
{
    /**
     * Init for webdav call
     * 
     * @param   string  $calendarData   ICS File data
     * @param   string  $objectUri      The URI
     * @param   object  $task           Current opentask, if any
     * @param   int     $calendarId     Calendar/Staff ID
     * @return  object  An Opentasks_values object with all values out of the given calendarData
     * @throws \InvalidArgumentException
     */
    public static function init_from_dav(string $calendarData, string $objectUri, stdClass $task=null, int $calendarId=null): Opentasks_values
    {
        $CI = CI_Controller::get_instance();
        
        $CI->load->library('import_parser/US_icalendar_parser', null, 'icalendar_parser');
        
        if (isset($calendarId)) {
            $CI->icalendar_parser->setStaff_to_id($calendarId);
        }
        
        $ok = $CI->icalendar_parser->parse_string($calendarData, 'ics');
        if ($ok!==false) {
            throw new \InvalidArgumentException('ICS Parser: '.$ok);
        }
        
        $ics_list = $CI->icalendar_parser->getList();
        if (count($ics_list)<=0) {
            throw new \InvalidArgumentException('ICS Parser did not get any data to read');
        }
        $obj = array_shift($ics_list);
        
        if ($task===null) {
            $obj->add_or_id = 'add';
            if (!isset($obj->project)) {
                $obj->project = $CI->icalendar_parser->getDefault_project_id();
            }
        } else {
            $obj->add_or_id = $task->id;
            $obj->do_not_save_addi = true;
            if (empty($obj->project)) {
                $obj->project = null;
            }
        }
        $obj->sabre_uri = $objectUri;
        $obj->sabre_calendar_data_obj = $CI->icalendar_parser->getVcalendar();
        
        return $obj;
    }

}
