/*
 *  Copyright 2017 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * This is a relation handler between:
 * * source : reference-table-content
 * * destination : reference-table-content or reference-table-content-root
 * 
 * It will change the "parent" attribute of the source, with the value of the destination (or empty if the destination is the root)
 * @private
 */
Ext.define('Ametys.plugins.cms.relations.SetParentContentRelationHandler', {
    extend: 'Ametys.plugins.cms.relations.SetContentAttributeRelationHandler',
    
    sourceTargetType: /^reference-table-content$/,
    
    destTargetType: /^reference-table-content(-root)?$/,
    
    supportedRelations: function(source, target)
    {
        // Are source simple contents and only simple contents ?
        var sourceContentTargets = Ametys.message.MessageTargetHelper.findTargets(source.targets, this.sourceTargetType, 1);
        if (sourceContentTargets.length == 0 || Ametys.message.MessageTargetHelper.findTargets(source.targets, Ext.bind(this._nonMatchingSource, this)).length > 0)
        {
            return [];
        }

        // Is target simple content and only simple content (or root of simple contents) ?
        var destContentTargets = Ametys.message.MessageTargetHelper.findTargets(target.targets, this.destTargetType, 1);
        if (destContentTargets.length != 1 || Ametys.message.MessageTargetHelper.findTargets(target.targets, Ext.bind(this._nonMatchingDest, this)).length > 0)
        {
            return [];
        }
        
        // Take the unique target
        var destContentTarget = destContentTargets[0];
        
        // Is there at least one target editable ?
        var authorized = false;
        if (destContentTarget.isMessageTarget && destContentTarget.getParameters().availableActions)
        {
            for (var w=0; w < this._workflowActionIds.length; w++)
            {
                if (Ext.Array.contains(destContentTarget.getParameters().availableActions, parseInt(this._workflowActionIds[w])))
                {
                    authorized = true;
                }
            }
        }
        else
        {
            // Can not check available actions, in doubt authorize the relationship (it will be eventually blocked later)
            authorized = true;
        }
        
        if (!authorized)
        {
            return [];
        }
        
        return [Ext.create('Ametys.relation.Relation', {
            type: Ametys.relation.Relation.MOVE,
            label: "{{i18n PLUGINS_CMS_RELATIONS_SETCONTENTATTRIBUTE_MOVE_LABEL}}",
            description: "{{i18n PLUGINS_CMS_RELATIONS_SETCONTENTATTRIBUTE_MOVE_DESCRIPTION}}",
            smallIcon: null,
            mediumIcon: null,
            largeIcon: null
        }), Ext.create('Ametys.relation.Relation', {
            type: Ametys.relation.Relation.REFERENCE,
            label: "{{i18n PLUGINS_CMS_RELATIONS_SETCONTENTATTRIBUTE_MOVE_LABEL}}",
            description: "{{i18n PLUGINS_CMS_RELATIONS_SETCONTENTATTRIBUTE_MOVE_DESCRIPTION}}",
            smallIcon: null,
            mediumIcon: null,
            largeIcon: null
        })];
    },
    
    link: function(source, target, callback, relationType)
    {
        var me = this,
            callback = callback || Ext.emptyFn,
            sourceContentTargets = source.getTargets(),
            contentIdsToMove = Ext.Array.map(sourceContentTargets, function(target) {return target.getParameters().id;})
            destContentTarget = target.getTargets()[0],
            positionInTargets = target.positionInTargets,
            isDestRoot = destContentTarget.getId() == Ametys.message.MessageTarget.REFERENCE_TABLE_CONTENT_ROOT,
            newParentContentId = isDestRoot ? "root" : destContentTarget.getParameters().id,
            leafContentTypeId = isDestRoot ? destContentTarget.getParameters().contentType : null;
          
        this.serverCall(
            "areValidMoves", 
            [contentIdsToMove, newParentContentId, leafContentTypeId],
            linkCb,
            {
                waitMessage: true,
                ignoreCallbackOnError: false
            }
        );
        
        function linkCb(response)
        {
            var validContents = response && response['validContents'] || {},
                isSameAttribute = Ext.Array.unique(Ext.Array.map(validContents, function(content) {return content.parentAttributeName;})).length == 1;
            
            if (response == null)
            {
                callback(false);
            }
            else if (validContents.length > 0 && isSameAttribute)
            {
                var attributePath = validContents[0].parentAttributeName;
                if (newParentContentId != "root")
                {
                    // New parent is not root => it is a real MOVE
                    var contentIdsToEdit = Ext.Array.map(validContents, function(content) {return content.id;}),
                        contentIdsToEditByType = {};
                    contentIdsToEditByType[Ametys.message.MessageTarget.REFERENCE_TABLE_CONTENT] = contentIdsToEdit;
                    me._linkChoiceCb(attributePath, 
                                     callback, 
                                     [newParentContentId] /* contentIdsToReference */, 
                                     contentIdsToEdit /* contentIdsToEdit */, 
                                     positionInTargets,
                                     contentIdsToEditByType,
                                     [] /* contentIdsToEditToRemove */, 
                                     null /* button */);
                }
                else
                {
                    // New parent is root => try to REMOVE the "parent" attribute
                    var contentIdsToEditToRemove = Ext.Array.map(validContents, function(content) {
                        return {
                            contentId: content.id,
                            referencingAttributePath: attributePath,
                            valueToRemove: content.parentAttributeValue
                        };
                    });
                    var contentIdsToEditByType = {}; // for MODFIFIED message bus in _linkCb2
                    contentIdsToEditByType[Ametys.message.MessageTarget.REFERENCE_TABLE_CONTENT] = [];
                    me._linkChoiceCb(attributePath,
                                     callback, 
                                     [] /* contentIdsToReference */, 
                                     [] /* contentIdsToEdit */, 
                                     positionInTargets,
                                     contentIdsToEditByType,
                                     contentIdsToEditToRemove, 
                                     null /* button */);
                }
            }
            else if (validContents.length > 0 /* isSameAttribute == false */)
            {
                 Ametys.log.ErrorDialog.display({
                    title: "{{i18n PLUGINS_CMS_RELATIONS_SETPARENTCONTENT_MOVE_NOSAMEMETADATA_TITLE}}",
                    text: "{{i18n PLUGINS_CMS_RELATIONS_SETPARENTCONTENT_MOVE_NOSAMEMETADATA}}",
                    category: this.self.getName()
                });
                callback(false);
            }
            else
            {
				// response['invalidContents'] and/or response['noRightContents']
                Ametys.log.ErrorDialog.display({
                    title: "{{i18n PLUGINS_CMS_RELATIONS_SETPARENTCONTENT_MOVE_NOVALID_TITLE}}",
                    text: "{{i18n PLUGINS_CMS_RELATIONS_SETPARENTCONTENT_MOVE_NOVALID_TEXT}}",
                    category: this.self.getName()
                });
                callback(false);
            }
        }
    }
});