/*
 *  Copyright 2023 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.
 */
/**
 * Class defining the condition tree panel for workflow actions
 */
 Ext.define('Ametys.plugins.workflow.trees.ConditionTreePanel', {
     extend: 'Ext.tree.Panel',
     
    constructor: function(config)
    {
        config.store = this._createStore();
        this.callParent(arguments);
    },
    
    onRender: function()
    {
        this.callParent(arguments);
        this.getColumns()[0].setWidth('100%');
    },
    
    /**
     * Create and set the conditionTreePanelstore
     * @returns {Object} a Ext.data.TreeStore for the tree
     * @private
     */
    _createStore: function()
    {
        var store = Ext.create('Ext.data.TreeStore', {
            model: Ametys.plugins.workflow.TransitionConditionModel,
            proxy: {
                type: 'ametys',
                role: 'org.ametys.plugins.workflow.dao.WorkflowConditionDAO',
                methodName: 'getConditionNodes',
                methodArguments: ["nodeId", "workflowName", "actionId"],
                reader: {
                    type: 'json',
                    rootProperty: 'conditions'
                }
            },
            listeners: {
                'beforeload': {fn: this._onBeforeLoad, scope: this},
                'load': {fn: this._onConditionTreeLoad, scope: this}
            },
            autoLoad: false,
            root: {
                type: 'root',
                title: "{{i18n PLUGINS_WORKFLOW_UITOOL_TRANSITION_CONDITION_ROOT_NAME}}",
                expanded: false
            }
        });
        
        return  store;
    },
    
    /**
     * Listener on store load, display number of nodes in the panel's title
     * @param {Object} store the store being loaded
     * @param {record} record the store content
     * @private
     */
    _onConditionTreeLoad: function(store, record)
    {
        this.expand();
        var conditionSize = 0;
        var loadedNodes = store.getData().items;
        if (record && loadedNodes.length < record.length)
        {
            conditionSize = record.length
        }
        else
        {
            for (i = 0; i < loadedNodes.length; i++)
            {
                if (!loadedNodes[i].getData().hasChildren)
                {
                    conditionSize++;
                }
            }
        }
        this.setTitle(this.getInitialConfig('title') + " ("+ conditionSize + ")");
    },
    /**
     * Set the workflow root parameters and load the store
     * @param {String} workflowName unique name of the current workflow
     * @param {Number} actionId unique name of the transition to display
     * @param {Function} [callback] function to call after refreshing
     */
    initRootNodeParameter: function (workflowName, actionId, callback)
    {
        this._workflowName = workflowName;
        this._actionId = actionId;
        this.getStore().load({node: this.getRootNode(), callback: Ext.bind(function() { this.getRootNode().expand(true); }, this)})
    },
    
    /**
     * Function called before loading the store to set the param
     * @param {Ext.data.Store} store The store
     * @param {Ext.data.operation.Operation} operation The object that will be passed to the Proxy to load the store
     * @private
     */
    _onBeforeLoad: function(store, operation)
    {
        operation.setParams(Ext.apply(operation.getParams() || {}, {
            nodeId: operation.node.getId(),
            workflowName: this._workflowName,
            actionId: parseInt(this._actionId)
        }));
    }
 });
 
 /**
 * Define the model for the condition properties
 */
Ext.define('Ametys.plugins.workflow.TransitionConditionModel', {
    extend: 'Ext.data.Model',
    
    fields: [
        {name: 'id', type : 'string'},
        {name: 'label', type: 'string'},
        {name: 'conditionId', type: 'string'},
        {
            name: 'leaf', 
            type: 'boolean',
            convert: function(value, record) {
                var data = record.data;
                if (data.root)
                {
                    return false;
                }
                return !data.hasChildren;
            }
        },
        {
            name: 'icon',
            calculate: function (data)
            {
               return " ";
            }
        }
    ]
});