import("system.vars");
import("system.tools");
import("Calendar_lib");
import("system.calendars");
import("system.neon");
import("system.text");

/**
 * Provides static methods for appointments.<br>
 * Do <u><b>not</b></u> create an instance of this.
 * 
 * @class
 */
function AppointmentUtils() {}

/**
 * Sets the participant status of the current users as <br>
 * given param state. <u>(Sets the user status for an <br>
 * appointment to accepted or declined.)</u><br>
 * 
 * @param {String} currentUserUri               <p>
 *                                              Current user identifier.<br>
 * @param {String} attendees                    <p>
 *                                              Attendees encoded as a multistring.<br>
 * @param {String} newState                     <p>
 *                                              The new status.<br>
 * @return {String}                             <p>
 *                                              Updated attendees encoded as multistring.<br>
 */
AppointmentUtils.setPartStat = function (currentUserUri, attendees, newState) {
    attendeesDecodedArray = text.decodeMS(attendees);

    for(var i = 0; i < attendeesDecodedArray.length; i++)
    {
        var decoded = text.decodeMS(attendeesDecodedArray[i])       
        if(decoded[0] ==  currentUserUri)
        {   
            var updated = new Array();       

            var isSet = false;
            for (var j = 0; j < decoded.length; j++)
            {           
                if (decoded[j].substr(0, 9) == "PARTSTAT:")
                {
                    updated.push("PARTSTAT:" + newState);
                    isSet = true;
                }
                else
                {
                    updated.push(decoded[j])
                }            
            }

            if (!isSet)
            {                    
               updated.push("PARTSTAT:" + newState);
            }                                 

            // Updaten Attendees
            var newAttendees = new Array();
            for (var x = 0; x < attendeesDecodedArray.length; x++)
            {
                 if (text.decodeMS(attendeesDecodedArray[x])[0] == currentUserUri)
                 {
                     newAttendees.push(text.encodeMS(updated))
                 }
                 else
                 {
                    newAttendees.push(attendeesDecodedArray[x])
                 }
            }
           break;
        }
    }

    return text.encodeMS(newAttendees);
}

/**
 * Sets the a new status for an users appointment.<br>
 * (Use case: when a exchange is running at the backend)<br>
 * 
 * @param {String} event                <p>
 *                                      Event which will be sent to the exchange.<br>
 *                                      (= the parsed appointment)<br>
 * @param {String} newState             <p>
 *                                      The new state which will be set.<br>
 *                                      (e.g.: "ACCEPT", "DECLINE", "")<br>
 */
AppointmentUtils.sendExchangedAction = function(event, newState)
{
    switch(newState)
    {
        case "ACCEPTED":
            newState = "ACCEPT";
            break;
        case "DECLINED":
            newState = "DECLINE";
            break;
        case "TENTATIVE":
            newState = "TENTATIVELYACCEPT";
            break;
        default :
            newState = "TENTATIVELYACCEPT";
    }
    
    
    var jsonEvent = JSON.parse(event);
    jsonEvent["X-ADITO-STATUSACTION"] = newState;    // "ACCEPT", "DECLINE", ""
    jsonEvent[calendars.AFFECTEDUSERS] = "";
    calendars.updateEntry(jsonEvent);
}

/**
 * Creates links in appointments.<br>
 * (e.g.: type: privat person and object: Christine Müller)
 * 
 * @param {String} pSysRecordstate              <p>
 *                                              The system record state<br>
 *                                              (e.g.: neon.OPERATINGSTATE_NEW)<br>
 * @param {String} pAppointmentState            <p>
 *                                              In case this is filled with<br>
 *                                              <b><i>neon.OPERATINGSTATE_NEW</i></b> it entails that<br>
 *                                              the current user is fetched and if he is<br>
 *                                              the organizer of the appointment<br>
 *                                              the appointment will be editable for<br>
 *                                              him otherwise he is only a attendee<br>
 *                                              and not able to edit the appointment.<br>
 * @param {String} pAppointmentIdParam          <p>
 *                                              Is used as parameter for calling the<br>
 *                                              <b><i>calendars.getEntry()</i></b> function in case<br>
 *                                              pSysRecordstate is neon.OPERATINGSTATE_NEW.<br>
 * @param {String} pAppointmentIdFieldValue     <p>
 *                                              Is used as parameter for calling the<br>
 *                                              <b><i>calendars.getEntry()</i></b> function in case<br>
 *                                              pSysRecordstate is neon.OPERATINGSTATE_EDIT.<br>
 *                                              <p>
 * @return {String}                             Returns the matching component state.
 */
AppointmentUtils.setAppointmentLinkComponentState = function(pSysRecordstate, pAppointmentState, pAppointmentIdParam, pAppointmentIdFieldValue)
{
    var entry;
    var newAppointment = false;
    
    if(pAppointmentState && pAppointmentState == neon.OPERATINGSTATE_NEW)
        newAppointment = true;
        
    else if(pSysRecordstate == neon.OPERATINGSTATE_NEW && pAppointmentIdParam)
        entry = calendars.getEntry(pAppointmentIdParam, null, null);

    else if(pSysRecordstate == neon.OPERATINGSTATE_EDIT)
        entry = calendars.getEntry(pAppointmentIdFieldValue, null, null);
    

    if(entry)
    {   
        var currentUserId = CalendarUtil.getEffectiveCalendarIdFromUser(tools.getCurrentUser());
        var organzierId = CalendarUtil.getEffectiveCalendarIdFromUser(tools.getUser(entry[calendars.ORGANIZER2]["cn"], tools.PROFILE_DEFAULT));
        var owner = text.decodeMS(entry["h"])[1].split(":")[1]

        if(currentUserId && currentUserId == organzierId || calendars.hasPermission([owner], calendars.VEVENT, "WRITE"))
            return neon.COMPONENTSTATE_EDITABLE;
        else
            return neon.COMPONENTSTATE_DISABLED;
    }
    else if(newAppointment)
        return neon.COMPONENTSTATE_EDITABLE
    else
        return neon.COMPONENTSTATE_DISABLED;
}