//#region основные файлы заявки
function MainFilesItemData(observer) {
    var that = this;

    var args = [];
    args.push(observer);
    args.push({
        group: 'mainfilelistrootcontainer',
        name: 'mainfilelist',
        selector: '#mainfilelistrootcontainer',
        useDefaultEvent: false,
        //initConflictAfterSubmit: {
        //    compareEqualsCurrentWithSubmitValue: false
        //},
    });
    ItemData.apply(this, args);

    this.removedMainFileList = [];

    this.addedDroppedFileList = [];
    this.attachedPasteScreenshotList = [];
}
MainFilesItemData.prototype = Object.create(ItemData.prototype);

MainFilesItemData.prototype.InitTaskRightsDisplayType = function () {
    this.taskRightsDisplayType = ItemDataHelper.TaskRightsDisplayType[$('#mainfilelistrootcontainer').attr(ItemData.taskRightsDisplayTypeKey)] || ItemDataHelper.TaskRightsDisplayType.None;
}

MainFilesItemData.prototype.GetBlockTitle = function () {
    return $(this._options.selector).find('[mainfilelisttitle]').clone().children().remove().end().text().replace(':', '').trim();
}
//part2 - пользовательская
MainFilesItemData.prototype.Append2 = function (userConnectionId, userId, userName, data, existUserConnectionId) {
    var $parent = $('[mainfilelisttitle]').parent();
    $parent.find('span.taskFormHub-blockInfo').remove();
    var $span = this.GetSpanTemplate(userConnectionId, userId);
    $parent.find('.taskFormHub-blockInfo-container').prepend($span);
    this.Highlight();
}
MainFilesItemData.prototype.ResetAll = function () {
    this.usersEditThisBlock = [];
    var $parent = $('[mainfilelisttitle]').parent();
    //удалить текущий span
    $parent.find('span.taskFormHub-blockInfo').remove();
    this.Unhighlight();
}
//part2 - пользовательская
MainFilesItemData.prototype.Reset2 = function (userConnectionId, userId, userName) {
    var $parent = $('[mainfilelisttitle]').parent();
    //удалить текущий span
    $parent.find('span.taskFormHub-blockInfo').remove();
    //если есть еще пользователи которые редактируют блок
    if (this.usersEditThisBlock.length > 0 && this.TaskRightsDisplayType() != ItemDataHelper.TaskRightsDisplayType.None) {
        //сделать новый span
        var $span = this.GetSpanTemplate(userConnectionId, userId);
        $parent.find('.taskFormHub-blockInfo-container').prepend($span);
        //подстветить
        this.Highlight();
    }
    else {
        this.Unhighlight();
    }
}
//функция подсветки блока
MainFilesItemData.prototype.Highlight = function () {
    $('#mainfilelistrootcontainer').addClass('taskFormHub-highlightBlock');
}
//функция убирает подсветку блока
MainFilesItemData.prototype.Unhighlight = function () {
    $('#mainfilelistrootcontainer').removeClass('taskFormHub-highlightBlock');
}

//MainFilesItemData.prototype.getFileIdsFromContainer = function (selector) {
//    return $(selector).find('li.file:not(.deletefile)').map(function (i, el) { return parseInt(el.getAttribute('id').replace('file','')); }).get() || [];
//};
MainFilesItemData.prototype.GetCurrentVal = function () {
    return $(this._options.selector).find('ul#files li.file:not(.deletefile)').filter(function(i,el){ return el.hasAttribute('id') }).map(function (i, el) { return parseInt(el.getAttribute('id').replace('file','')); }).get() || [];
}
MainFilesItemData.prototype.IsChanged = function () {
    var oldValue = this.GetOldValue();
    var curValue = this.GetCurrentVal();
    return !ItemDataHelper.ArraysIsEquals(curValue, oldValue) || this.removedMainFileList.length > 0 || this.addedDroppedFileList.length > 0 || this.attachedPasteScreenshotList.length > 0;
}

MainFilesItemData.prototype.RemoveConflictMessage = function () {
    this.isConflict = false;
    this.$conflictMessageElement = undefined;
    $(this._options.selector).find('[conflict-block="' + this._options.name + '"]').remove();
}

MainFilesItemData.prototype.InitConflictAfterSubmit = function (submitData) {
    var that = this;

    //удалить старую инфу
    this.isConflict = false;
    this.RemoveConflictMessage();
  
    var $selector = $(this._options.selector);
    var $ulFiles = $selector.find('ul#files');
    var canRemove = $ulFiles.find('li.file a.canRemoveMainFile').length > 0;
    $ulFiles.empty();

    var tmpMyRemovedFiles = this.removedMainFileList.slice();
    this.removedMainFileList = [];

    for (var i = 0; i < submitData.length; i++) {
        var submitItem = submitData[i];

        var isMyRemoved = false;
        if (tmpMyRemovedFiles.indexOf(submitItem.FileId) != -1) {
            that.removedMainFileList.push(submitItem.FileId);
            isMyRemoved = true;
        }

        var $li = $('<li class="file" id="file' + submitItem.FileId + '"></li>');
        if (isMyRemoved) {
            $li.addClass('deletefile');
        }
        var fileExtension = submitItem.FileName.split('.').pop();
        $li.append('<img class="icon16" src="img/mime/' + fileExtension + '_16.gif" />');
        var $aViewfile = $('<a class="' + (isMyRemoved ? 'selectdeletedfile' : 'noul') + ' saveFile" href="Task/ViewFile/' + submitItem.FileId + '">' + (submitItem.FileName.length > 64 ? ('...' + submitItem.FileName.substring(0, submitItem.FileName.length - 64)) : submitItem.FileName) + '</a>');
        if (fileExtension == 'jpg' || fileExtension == 'gif' || fileExtension == 'png' || fileExtension == 'bmp' || fileExtension == 'jpeg' || fileExtension == 'ico' || fileExtension == 'pdf') {
            $aViewfile.attr('data-lightbox', $('#id').val());
            $aViewfile.attr('data-title', submitItem.FileName.toLowerCase());
        }
        $li.append($aViewfile);
        var $aSaveFile = $('<a class="noul saveFile" href="Task/ViewFile/' + submitItem.FileId + '?save=true"><img class="saveimg" src="img/download.png"/></a>');
        $li.append($aSaveFile);
        if (canRemove) {
            $li.append('<a class="noul canRemoveMainFile" href="#" onclick="return removeFile('+submitItem.FileId+');"><img src="img/trash.gif" /></a>')
        }
        $li.append('<span class="details">' + submitItem.Creator + '</span>');

        $ulFiles.append($li);
    }

    this.SetOldValue($ulFiles.find('li.file').map(function (i, el) { return parseInt(el.getAttribute('id').replace('file', '')); }).get() || []);
    this.SendBlockChange();


    var $notconflictMessage = $(this.tmpl_notconflictMessageBase({ blockName: this._options.name }));
    //добавить новую инфу
    $(this._options.selector).find('[mainfilelisttitle]').parent().append($notconflictMessage);

    return false;
}

MainFilesItemData.prototype.removeMainFile = function (id) {
    id = parseInt(id);
    if (!id) {
        return;
    }

    var index = this.removedMainFileList.indexOf(id);
    if (index == -1) {
        //добавляем
        this.removedMainFileList.push(id);
    }
    else {
        //удаляем
        this.removedMainFileList.splice(index, 1);
    }
    this.SendBlockChange();
}

MainFilesItemData.prototype.addDroppedFile = function (id) {
    id = parseInt(id);
    if (!id) {
        return;
    }

    if (this.addedDroppedFileList.indexOf(id) == -1) {
        this.addedDroppedFileList.push(id);
        this.SendBlockChange();
    }   
}
MainFilesItemData.prototype.removeDroppedFile = function (id) {
    id = parseInt(id);
    if (!id) {
        return;
    }

    var index = this.addedDroppedFileList.indexOf(id);
    if (index != -1) {
        this.addedDroppedFileList.splice(index, 1);
        this.SendBlockChange();
    }
}

MainFilesItemData.prototype.attachPasteScreenshot = function (n) {
    n = parseInt(n);
    if (!n) {
        return;
    }

    if (this.attachedPasteScreenshotList.indexOf(n) == -1) {
        this.attachedPasteScreenshotList.push(n);
        this.SendBlockChange();
    } 
}
MainFilesItemData.prototype.removePasteScreen = function (n) {
    n = parseInt(n);
    if (!n) {
        return;
    }

    var index = this.attachedPasteScreenshotList.indexOf(n);
    if (index != -1) {
        this.attachedPasteScreenshotList.splice(index, 1);
        this.SendBlockChange();
    }
}
//#endregion