{% extends "@UVDeskCoreFramework/Templates/layout.html.twig" %}

{% block title %}
    {% if app.request.get('id') %}
        {{ 'Edit Workflow' | trans }}
    {% else %}
        {{ 'Add Workflow' | trans }}
    {% endif %}
{% endblock %}

{% block internalcss %}
    @media(max-width: 767px) {
        #company-workflow > .steps {
            display: none;
        }
    }

    @media(max-width: 579px) {
        #company-workflow > h3 {
            margin-right: 80px;
        }

        #company-workflow > h3 > a {
            position: absolute;
            top: 0px;
            right: 10px;
        }
    }

    .has-error button.btn {
        border-color: #cc5965;
    }
{% endblock %}

{% block pageContent %}
    <style>
        .workflow-conditions-body .workflow-condition:first-child .uv-workflow-hr-plank {
            display: none;
        }
        .grammarly-fix-message-container {
			overflow: visible !important;
		}
		.grammarly-fix-message {
			max-width: 120%;
		}
        .textarea-fix-action {
            max-width: 500px !important;
        }
    </style>
    <!-- Inner Section -->
    <div class="uv-inner-section">
        {# Append Panel Aside #}
		{% set asideTemplate = 'Webkul\\UVDesk\\CoreFrameworkBundle\\Dashboard\\AsideTemplate' %}
		{% set asideSidebarReference = 'Webkul\\UVDesk\\CoreFrameworkBundle\\UIComponents\\Dashboard\\Panel\\Sidebars\\Productivity' %}

		{{ uvdesk_extensibles.getRegisteredComponent(asideTemplate).renderSidebar(asideSidebarReference) | raw }}
        
        <!-- View -->
        <div class="uv-view {% if app.request.cookies and app.request.cookies.get('uv-asideView') %}uv-aside-view{% endif %}">
            <!-- Form -->
            {% if app.request.get('id') is not empty %}
                <h1>{{ 'Edit Workflow'|trans }}</h1>
                <form class="workflow-form" name="form-workflow" method="POST" action="{{ path('workflows_editaction', {'id': app.request.get('id')}) }}">
            {% else %}
                <h1>{{ 'New Workflow'|trans }}</h1>
                <form class="workflow-form" name="form-workflow" method="POST" action="{{ path('workflows_addaction') }}">
            {% endif %}
                <!-- Workflow Description Section -->
                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Name'|trans }}</label>
                    <div class="uv-field-block">
                        <input name="name" class="uv-field" type="text" value="{{ formData.name is defined ? formData.name : '' }}">
                        <p class="uv-field-message">{% if error.name is defined %}{{ error.name }}{% endif %}</p>
                    </div>
                </div>

                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Description'|trans }}</label>
                    <div class="uv-field-block grammarly-fix-message-container">
                        <textarea name="description" class="uv-field grammarly-fix-message">{{ formData.description is defined ? formData.description : '' }}</textarea>
                        <p class="uv-field-message">{% if error.description is defined %}{{ error.description }}{% endif %}</p>
                    </div>
                </div>

                <div class="uv-element-block">
                    <label class="uv-field-label">{{ 'Workflow Status'|trans }}</label>
                    <div class="uv-element-block">
                        <label>
                            <div class="uv-checkbox">
                                <input name="status" type="checkbox" {{ formData.status is defined and formData.status == 'on' ? 'checked' : '' }}>
                                <span class="uv-checkbox-view"></span>
                            </div>
                            <span class="uv-checkbox-label">{{ 'Workflow is Active'|trans }}</span>
                        </label>
                    </div>
                </div>

                <div class="uv-hr"></div>
                <!-- // Workflow Description Section -->


                <!-- Workflow Events Section -->
                <div id="events" class="uv-field-workflow">
                    <label class="uv-field-label">{{ 'Events'|trans }}</label>
                    <span class="uv-field-info">{{ "An event automatically triggers to check conditions and perform a respective pre-defined set of actions"|trans }}</span>

                    <div class="workflow-event-body"></div>
                    <div class="uv-workflow-buttons">
                        <a class="uv-btn-tag btn-add" href="#">
                            <span class="uv-icon-add-dark"></span> {{'Add More'|trans}}
                        </a>
                    </div>
                </div>

                <div class="uv-hr"></div>
                <!-- // Workflow Events Section -->

                <!-- Workflow Conditions Section -->
                <div id="conditions" class="uv-field-workflow" >
                    <label class="uv-field-label">{{ 'Conditions'|trans }}</label>
                    <span class="uv-field-info">{{ 'Conditions are set of rules which checks for specific scenarios and are triggered on specific occasions'|trans }}</span>

                    <div class="workflow-conditions-body"></div>
                    <div class="uv-workflow-buttons">
                        <a class="uv-btn-tag btn-or" href="#">
                            <span class="uv-icon-add-dark"></span> {{ 'OR'|trans }}
                        </a>
                        <a class="uv-btn-tag btn-and" href="#">
                            <span class="uv-icon-add-dark"></span> {{ 'AND'|trans }}
                        </a>
                    </div>
                </div>
                <!-- // Workflow Conditions Section -->
                <div class="uv-hr"></div>
                


                <!-- Workflow Actions Section -->
                <div id="actions" class="uv-element-block uv-field-workflow">
                    <label class="uv-field-label">{{ 'Actions'|trans }}</label>
                    <span class="uv-field-info">{{ 'An action not only reduces the workload but also makes it quite easier for ticket automation'|trans }}</span>

                    <div class="workflow-action-body"></div>
                    <div class="uv-workflow-buttons">
                        <a class="uv-btn-tag btn-add" href="#">
                            <span class="uv-icon-add-dark"></span> {{ 'Add More'|trans }}
                        </a>
                    </div>
                </div>
                <!-- // Workflow Actions Section -->

                <!-- CTA -->
                {# <input type="submit" class="uv-btn" href="#" value="Save Workflow"> #}
                <button type="submit" name="submit" class="uv-btn" href="#">{% if app.request.get('id') is not empty %}{{ 'Save Workflow'|trans }}{% else %}{{ 'Add Workflow'|trans }}{% endif %}</button>
                <!-- // CTA -->
            </form>
            <!-- Form -->
        </div>
        <!-- // View -->
    </div>
    <!-- // Inner Section -->
{% endblock %}

{% block footer %}
    {{ parent() }}

    <script type="text/javascript">
        _.extend(Backbone.Validation.patterns, {
          stringPattern: /[a-z0-9]/i,
        });

        _.extend(Backbone.Validation.callbacks, {
            valid : function (view, attr, selector) {
                $('[name="'+attr+'"]').closest('.uv-field-block').find('.uv-field-message').html('').fadeOut(0);
            },
            invalid : function (view, attr, error, selector) {
                $('[name="'+attr+'"]').closest('.uv-field-block').find('.uv-field-message').html(error).fadeIn(0);
            }
        });

        if(typeof(sB) == 'undefined'){
          var sB = {};
        }

        sB.WorkflowCollection = Backbone.Collection.extend({
            baseUrl: "{{ path('ajax_service_call') }}",
            fetchResult: function(dataMatch) {
            this.url = this.baseUrl;
            return this.fetch({ 'data' : {
                'service': 'email.service',
                'call': 'getEmailPlaceHolders',
                'options': { 'match': dataMatch },
            }});
        }});
        sB.workflowCollection = new sB.WorkflowCollection();

        sB.WorkflowModel = Backbone.Model.extend({
            validation: {
                name: {
                    required: true,
                    pattern: 'stringPattern',
                    msg: "{{ 'Please enter a valid name.'|trans }}"
                },
            },
            validateSelect: function(value, attr, computedState) {
                var currentSelectValue = $('select[name="'+ attr + '"]').find(':selected').length;
                if (!value) {
                    return "{{ 'Please select a value.'|trans }}";
                }
            },
            validateSelectMultiple: function(value, attr, computedState) {
                var currentSelectValue = $('[name="'+ attr + '"]').length;
                if (!value) {
                    return "{{ 'Please select a value.'|trans }}";
                }
            },
            validateSelectText: function(value, attr, computedState) {
                if (!value) {
                    return "{{ 'Please add a value.'|trans }}";
                }
            }
        });

        sB.WorkflowView = Backbone.View.extend({
            el: '.uv-view',
            initialize: function() {
                this.model = new sB.WorkflowModel();
                Backbone.Validation.bind(this);
            },
            events: {
                'submit form[name="form-workflow"]': 'processWorkflow',
            },
            processWorkflow: function(e) {
                var disabledCollection = this.$el.find('form').find('[disabled]');
                if ($(disabledCollection).length > 0) {
                    $.each($(disabledCollection), function(index, nodeElement) {
                        $(nodeElement).removeAttr('disabled');
                    });
                }

                this.model.set(this.$el.find('form').serializeObject());

                var self = this;
                filterArray = ['name'];
                // Populate Filter Array - Events and Actions are required fields

                // Event
                this.$('.wfEvents').each(function(key, value) {
                    filterArray.push($(value).attr('name'));
                    self.model.validation[$(value).attr('name')] = 'validateSelect';
                });
                this.$('.wfEventTriggers').each(function(key, value) {
                    filterArray.push($(value).attr('name'));
                    self.model.validation[$(value).attr('name')] = 'validateSelect';
                });

                // Conditions
                if ($("[name='events[0][event]']").val() == 'ticket' || $("[name='events[0][event]']").val() == 'task') {
                    this.$('.wfCondition').each(function(key, value) {
                        filterArray.push($(value).attr('name'));
                        self.model.validation[$(value).attr('name')] = 'validateSelect';
                    });
                    this.$('.wfConditionMatch').each(function(key, value) {
                        filterArray.push($(value).attr('name'));
                        self.model.validation[$(value).attr('name')] = 'validateSelect';
                    });
                    this.$('.wfConditionValue').each(function(key, value) {
                        if ($(this).attr('name') == undefined) {
                            return;
                        }
                        filterArray.push($(value).attr('name'));
                        self.model.validation[$(value).attr('name')] = 'validateSelectText';
                    });
                }

                // Actions
                this.$('.wfAction').each(function(key, value) {
                    filterArray.push($(value).attr('name'));
                    self.model.validation[$(value).attr('name')] = 'validateSelect';
                });
                this.$('.wfActionMultiple').each(function(key, value) {
                    filterArray.push($(value).attr('name'));
                    self.model.validation[$(value).attr('name')] = 'validateSelectMultiple';
                });
                this.$('.wfActionValue').each(function(key, value) {
                    if ($(this).attr('name') == undefined) {
                        return;
                    }

                    filterArray.push($(value).attr('name'));
                    self.model.validation[$(value).attr('name')] = 'validateSelectText';
                });

                if (this.validateData(filterArray)) {
                    return true;
                } else {
                    e.preventDefault();
                    if ($(disabledCollection).length > 0) {
                        $.each($(disabledCollection), function(index, nodeElement) {
                            $(nodeElement).attr('disabled', 'disabled');
                        });
                    }
                }
            },
            validateData: function(filterArray) {
                return this.model.isValid(filterArray);
            },
            updateActive: function(e){
                this.$('div.step-info').each(function() {
                    $(this).addClass('active');
                    if ($(this).attr('data-href') == self.$(e.target).attr('href'))
                        return false;
                });
            }
        });
        sB.workflowView = new sB.WorkflowView();

        $.fn.serializeObject = function () {
            "use strict";
            var a = {}, b = function (b, c) {
                var d = a[c.name];
                "undefined" != typeof d && d !== null ? $.isArray(d) ? d.push(c.value) : a[c.name] = [d, c.value] : a[c.name] = c.value
            };
            return $.each(this.serializeArray(), b), a
        };
    </script>

    {{ include('@UVDeskAutomation//Workflow//events.html.twig') }}
    {{ include('@UVDeskAutomation//Workflow//conditions.html.twig') }}
    {{ include('@UVDeskAutomation//Workflow//actions.html.twig') }}

{% endblock %}
