/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) 2004-2010 Open-Xchange, Inc.
 * Mail: info@open-xchange.com 
 * 
 * @author Viktor Pracht <viktor.pracht@open-xchange.com>
 * @author Suphi Basdemir <suphi.basdemir@open-xchange.com> 
 * 
 */

function MoveCopy() {
    this.currentObjects = null;
    this.timestamp = "";
    this.objId = "";
    this.oldFolderid = "";
    this.newFolderid = "";
    this.ajaxUrl = "";
    this.objForUpdate = {};
    this.currentModule = "";
    this.finalObjects = [];
}

MoveCopy.prototype = {
    begin: function(currentModule, objects) {
        this.currentModule = currentModule || activemodule;
        if(objects) { this.currentObjects=objects;
        } else { this.currentObjects = menuselectedobjects; }
        this.module = activemodule;
    },
    endMoving: function(selectedfolderid) {
        var Self=this;
        if(this.currentModule == "mail" || this.currentModule == "contacts" || this.currentModule == "tasks" || this.currentModule == "infostore") {
            var newfolder=selectedfolderid;
            var request=[];
            this.finalObjects = [];
            var mapping = OXCache.moduleMappings[this.currentModule];
            for(var i in this.currentObjects) {
                var tmpKey=this.currentObjects[i];
                var tmpTime = tmpKey.timestamp;
                var tmpObj_Hashed = {
                    module: this.currentModule,
                    id: tmpKey.id,
                    folder_id: tmpKey.folder || tmpKey.folder_id
                };
                tmpObj_Hashed = mapping.createKeyFromObject(tmpObj_Hashed);
                if(!tmpTime) {
                    var tmpObj=OXCache.cachedObjects.get(tmpObj_Hashed);
                    tmpTime=tmpObj.timestamp;
                }
                if(tmpKey.folder_id != newfolder) {
                    request.push({
                       action    : "update", 
                       module    : tmpKey.module, 
                       id        : tmpKey.id,
                       folder    : tmpKey.folder_id,
                       timestamp : tmpTime,                       
                       data      : { folder_id: newfolder }
                    });
                    this.finalObjects.push(tmpObj_Hashed);
                } 
            }
            if (request.length) {
                json.put(AjaxRoot + "/multiple?session=" + session + "&continue=true", request, null, function (reply) {
                    for (var i = 0; i < reply.length; i++) {
                        if (reply[i].error) {
                            newServerError(reply[i]);
                        }
                    }
                    mapping.deleteObjectsInternal(Self.finalObjects);                    
                    mapping.createObjectsInternal(
                        [{ folder_id : selectedfolderid }]);
                    // updating the unread counters
                    if (Self.currentModule == "mail") {
                        var folderMap = {};
                        for (var i = 0; i < Self.finalObjects.length; i++) {
                            folderMap[Self.finalObjects[i].folder_id] = true;
                        }
                        folderMap[newfolder] = true;
                        var folders = [];
                        for (var i in folderMap) folders.push(i);
                        ox.api.folder.refresh({ folders: folders });
                    }
                    //TODO REMOVE FROM NEW AND CREATE IN NEW MAIL AND CHECK DETAIL
                    //TODO don't forget Unified Mail
                });
            }
            return;
        }
        Self.newFolderid = selectedfolderid;
        Self.objForUpdate.folder_id = Self.newFolderid;
        Self.updateTimestamp();
        var request = [], items = [];
        for (var i in Self.currentObjects) {
            var item = Self.currentObjects[i];
            var myfolder =item.folder;
            if(!myfolder) {
                myfolder=item.folder_id;
            }
            //DAYVIEW 
            if(!myfolder) {
                myfolder=item.folderID;
            }
            if(myfolder != Self.objForUpdate.folder_id) {
                request.push({action: "update", module: Self.module,
                    id: item.id, folder: myfolder, timestamp: Self.timestamp,
                    data: {folder_id: selectedfolderid}});
                items.push(item);
            }
        }
        if(request.length > 0) {
           json.put(AjaxRoot + "/multiple?session=" + session + "&continue=true",
               request, null, function(updatedFields) {
                   var updateview=false;
                   var iserror = false;
                   var conflictingrequests=[];
                   var sendconflicts=[];
                   function success() {
                       switch (Self.currentModule) {
                           case "calendar":
                               if (currentpath2[1] == "detail") {
                                   selectedAppointment.folder = selectedfolderid;
                                   detailAppointmentOnload();
                               } else if (currentpath2[1] != "list" && calendarGrid && calendarGrid.storage) {
                                   if(!configGetKey("gui.calendar.allfolders")) {
                                       calendarGrid.deleteIDs(Self.currentObjects);
                                   }
                               } else {
                                   setTimeout(function() { storageCache.update(); }, 0);
                               }
                               // notify via event
                               triggerEvent("OX_After_MoveCopy_Appointment");
                               break;
                       }
                   }
                   function newignore(myrequest) {
                       return function() {
                           myrequest.data.ignore_conflicts=true;
                           sendconflicts.push(myrequest);
                       };
                   }
                   function doConflict(myindex) {
                       return function() {
                           if (conflictingrequests.length>myindex) {
                               ConflictsPopup.open(
                                   conflictingrequests[myindex].object,
                                   conflictingrequests[myindex].conflicts,
                                   doConflict(myindex+1), null,
                                   newignore(conflictingrequests[myindex].request));
                           } else {
                               json.put(AjaxRoot + "/multiple?session=" + session + "&continue=true", sendconflicts, null, function() {
                                   success();
                               });
                           }
                       };
                   }
                   for(var i=0;i<updatedFields.length;i++) {
                       if(updatedFields[i].error) {
                           newServerError(updatedFields[i]);
                           iserror = true;
                       } else {
                           updateview=true;
                           if(Self.currentModule == "calendar" && updatedFields[i].data && updatedFields[i].data.conflicts) {
                               conflictingrequests.push({
                                   object: items[i],
                                   request: request[i],
                                   conflicts : updatedFields[i].data.conflicts
                               }); 
                           }
                       }
                   }
                   if(updateview) {
                       if(conflictingrequests.length>0) {
                           doConflict(0)();
                       } else {
                           success();
                       }
                   }
               }
           );
        }
    },
    endCopy: function(selectedfolderid) {
        var Self = this;
        if (this.currentModule == "mail" || this.currentModule == "contacts" || this.currentModule == "tasks" || this.currentModule == "infostore") {
            var newfolder=selectedfolderid;
            var request=[];
            for(var i in this.currentObjects) {
                var tmpKey=this.currentObjects[i];
                request.push({
                    action: "copy", 
                    module: tmpKey.module, 
                    id: tmpKey.id,
                    folder: tmpKey.folder_id, 
                    timestamp: tmpKey.timestamp,
                    data: { folder_id: selectedfolderid }
                });
            }
            if (request.length) {
               json.put(AjaxRoot + "/multiple?session=" + session + "&continue=true",request, 
               null, function(updatedFields) {
                      //TODO
                   if (updatedFields && updatedFields[0] && updatedFields[0].error) { 
                           newServerError(updatedFields[0]); 
                   } else {
                        var mapping = OXCache.moduleMappings[Self.currentModule];
                        mapping.createObjectsInternal([{ folder_id : selectedfolderid }]);
                        if (Self.currentModule == "mail") {
                            ox.api.folder.refresh({ folders: [newfolder] });
                        }
                       //TODO REMOVE FROM NEW AND CREATE IN NEW MAIL AND CHECK DETAIL
                       //TODO don't forget Unified Mail
                   }
                });
            }
            return;
        }
        Self.newFolderid = selectedfolderid;
        Self.objForUpdate.folder_id = Self.newFolderid;
        Self.updateTimestamp();
        var request = [];
        for (var i in Self.currentObjects) {
            var item = Self.currentObjects[i];
            request.push({action: "copy", module: Self.module, id: item.id,
                folder: item.folder, timestamp: Self.timestamp,
                data: {folder_id: selectedfolderid}});
        }
        json.put(AjaxRoot + "/multiple?session=" + session + "&continue=true",
            request, null, function(updatedFields) {
                if(updatedFields && updatedFields[0] && updatedFields[0].error) {
                    newServerError(updatedFields[0]);
                } else {
                    if (Self.module == "contacts") {
                        if(currentpath2[1] == "cards") {
                            objContactFunctions.resetContactCardCache();
                        }
                    }
                    
                    
                }
            });
    },
    updateTimestamp: function() {
        if(currentpath2[0] == "mail" && currentpath2[1]=="detail") {
            // mail/detail: from global var
            this.timestamp = mailFetchTimestamp;
        }
        else if (currentfullpath == "calendar/team/day") {
            // we have no better data (free-busy return zero)
            // workaround: now plus 1 hour
            this.timestamp = (new Date()).getTime() + 1000 * 60 * 60;
        }
        else {
            // default action: use cache timestamp
            this.timestamp = storageCache.current.timestamp;
        }
    }
};

var objMoveCopy = new MoveCopy();

/*
 * Register Events for MOVE
 * */
register('OX_Mail_Move', 
    function() {
        objMoveCopy.begin();
    }
);

register('OX_Calendar_Move', 
    function() {
        objMoveCopy.begin();
    }
);

register('OX_Contact_Move', 
    function() {
        objMoveCopy.begin();
    }
);


register('OX_InfoStore_Move', 
    function() {
        objMoveCopy.begin('infostore');
    }
);

register('OX_Task_Move', 
    function() {
        objMoveCopy.begin('tasks');
    }
);

register('OX_Object_Move', 
    function(selectedfolderid) {
        objMoveCopy.endMoving(selectedfolderid);
    }
);


/*
 * Register Events for COPY
 * */
register('OX_Mail_Copy', 
    function() {
        objMoveCopy.begin();
    }
);

register('OX_Contact_Copy', 
    function() {
        objMoveCopy.begin();
    }
);

register('OX_Object_Copy', 
    function(selectedfolderid) {
        objMoveCopy.endCopy(selectedfolderid);
    }
);

fileloaded();