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

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

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

/**
 * Used to save a address via DAV
 *
 * @property    My_Controller           $CI                     The main CI object
 */
class Address_dav_values extends Address_values
{
    /**
     * Init for webdav call
     * 
     * @param   string  $cardData       VCF File data
     * @param   string  $objectUri      The URI
     * @param   object  $address           Current address, if any
     * @return  object  An Address_values object with all values out of the given cardData
     * @throws \InvalidArgumentException
     */
    public static function init_from_dav(string $cardData, string $objectUri, stdClass $address=null): Address_values
    {
        /**
         * @var My_Controller           $CI
         */
        $CI = CI_Controller::get_instance();
        
        $CI->load->library('import_parser/US_address_parser', null, 'addresses_parser');
        
        $ok = $CI->addresses_parser->parse_string($cardData, 'vcf');
        if ($ok!==false) {
            throw new \InvalidArgumentException('VCF Parser: '.$ok);
        }
        
        $vcf_list = $CI->addresses_parser->getList();
        if (count($vcf_list)<=0) {
            throw new \InvalidArgumentException('VCF Parser did not get any data to read');
        }
        $obj = array_shift($vcf_list);
        
        if ($address===null) {
            $obj->add_or_id = 'add';
        } else {
            $obj->add_or_id = $address->id;
            $obj->do_not_save_addi = true;

            $raw_data_object = $CI->addresses_parser->get_raw_data_object();
            $obj->filter_fields = $raw_data_object;
            
        }
        $obj->sabre_uri = $objectUri;
        $obj->sabre_calendar_data_obj = $CI->addresses_parser->getVcard();
        
        return $obj;
    }

}
