aboutsummaryrefslogtreecommitdiffstats
path: root/gui-editors/gui-editor-apex/src/main/resources/webapp/js/ApexPolicyEditForm.js
blob: edaf7b738dc3efe4d2eade8897c3e428b5320a40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2020-2021 Nordix Foundation.
 *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

import {apexUtils_removeElement, apexUtils_emptyElement, apexUtils_areYouSure, scrollToTop} from "./ApexUtils";
import {dropdownList, dropdownList_ChangeOptions} from "./dropdownList";
import {ajax_get, ajax_delete, ajax_getWithKeyInfo, ajax_post, ajax_put} from "./ApexAjax";
import {policyTab_reset} from "./ApexPolicyTab";
import { editPolicyForm_State_generateStateDiv, editPolicyForm_State_getStateBean } from "./ApexPolicyEditForm_State";
import { formUtils_generateDescription, formUtils_generateUUID } from "./ApexFormUtils";
import {keyInformationTab_reset} from "./ApexKeyInformationTab";

function editPolicyForm_createPolicy(formParent) {
    editPolicyForm_editPolicy_inner(formParent, null, "CREATE");
}

function editPolicyForm_deletePolicy(parent, name, version) {
    var message = "Are you sure you want to delete Policy \"" + name + ":" + version + "\"?";
    if (apexUtils_areYouSure(message)) {
        var requestURL = restRootURL + "/Policy/Delete?name=" + name + "&version=" + version;
        ajax_delete(requestURL, function(data) {
            apexUtils_removeElement("editPolicyFormDiv");
            policyTab_reset();
            keyInformationTab_reset()
        });
    }
}

function editPolicyForm_viewPolicy(formParent, name, version) {
    // get the policy
    var requestURL = window.restRootURL + "/Policy/Get?name=" + name + "&version=" + version;
    ajax_getWithKeyInfo(requestURL, "apexPolicy", function(policy) {
        editPolicyForm_editPolicy_inner(formParent, policy, "VIEW");
    }, "policyKey");
}

function editPolicyForm_editPolicy(formParent, name, version) {
    // get the policy
    var requestURL = window.restRootURL + "/Policy/Get?name=" + name + "&version=" + version;
    ajax_getWithKeyInfo(requestURL, "apexPolicy", function(policy) {
        editPolicyForm_editPolicy_inner(formParent, policy, "EDIT");
    }, "policyKey");
}

function editPolicyForm_editPolicy_inner(formParent, policy, viewOrEdit) {
    // Get all contextSchemas too
    var requestURL = window.restRootURL + "/ContextSchema/Get?name=&version=";
    var contextSchemas = new Array();
    ajax_get(requestURL, function(data2) {
        for (let value of data2.messages.message) {
            var contextSchema = JSON.parse(value).apexContextSchema;
            contextSchemas.push({
                "name" : contextSchema.key.name,
                "version" : contextSchema.key.version,
                "displaytext" : contextSchema.key.name + ":" + contextSchema.key.version,
                "contextSchema" : contextSchema
            });
        }
        // Get all tasks
        requestURL = window.restRootURL + "/Task/Get?name=&version=";
        var tasks = new Array();
        ajax_get(requestURL, function(data3) {
            for (let value of data3.messages.message) {
                var task = JSON.parse(value).apexTask;
                tasks.push({
                    "name" : task.key.name,
                    "version" : task.key.version,
                    "displaytext" : task.key.name + ":" + task.key.version,
                    "task" : task
                });
            }
            // Get all ContextAlbums
            requestURL = window.restRootURL + "/ContextAlbum/Get?name=&version=";
            var albums = new Array();
            ajax_get(requestURL, function(data4) {
                for (let value of data4.messages.message) {
                    var album = JSON.parse(value).apexContextAlbum;
                    albums.push({
                        "name" : album.key.name,
                        "version" : album.key.version,
                        "displaytext" : album.key.name + ":" + album.key.version,
                        "album" : album
                    });
                }
                // Get all Events
                requestURL = window.restRootURL + "/Event/Get?name=&version=";
                var events = new Array();
                ajax_get(requestURL, function(data5) {
                    for (let value of data5.messages.message) {
                        var event = JSON.parse(value).apexEvent;
                        events.push({
                            "name" : event.key.name,
                            "version" : event.key.version,
                            "displaytext" : event.key.name + ":" + event.key.version,
                            "event" : event
                        });
                    }
                    editPolicyForm_activate(formParent, viewOrEdit, policy, tasks, events, albums, contextSchemas);
                });
            });
        });
    });
}

function editPolicyForm_activate(parent, operation, policy, tasks, events, contextAlbums, contextItemSchemas) {
    apexUtils_removeElement("editPolicyFormDiv");
    var formParent = document.getElementById(parent);

    //Testing purposes
    if(formParent === null) {
        formParent = document.createElement("testFormParent");
    }
    apexUtils_emptyElement(parent);

    var createEditOrView = "";

    if (!operation) {
        console.warn("No operation specified for PolicyForm form")
    } else {
        createEditOrView = operation.toUpperCase();
    }

    if (createEditOrView == "EDIT" || createEditOrView == "VIEW") {

        if (!policy) {
            console.warn("Invalid value (\"" + policy + "\") passed as a value for \"policy\" for PolicyForm form.");
        } else {
            if (!policy.policyKey || !policy.policyKey.name || policy.policyKey.name == "") {
                console.warn("Invalid value (\"" + policy.policyKey.name
                        + "\") passed as a value for \"name\" for PolicyForm form.");
            }
            if (!policy.policyKey || !policy.policyKey.version || policy.policyKey.version == "") {
                console.warn("Invalid value (\"" + policy.policyKey.version
                        + "\") passed as a value for \"version\" for PolicyForm form.");
            }
            if (!policy.uuid || policy.uuid == "") {
                console.warn("Invalid value (\"" + policy.uuid
                        + "\") passed as a value for \"uuid\" for PolicyForm form.");
            }
        }
    } else {
        console.warn("Invalid operation (\"" + operation
                + "\") specified for PolicyForm form. Only \"Create\", \"Edit\" and \"View\" operations are supported");
    }

    var contentelement = document.createElement("editPolicyFormDiv");
    var formDiv = document.createElement("div");
    contentelement.appendChild(formDiv);
    formDiv.setAttribute("id", "editPolicyFormDiv");
    formDiv.setAttribute("class", "editPolicyFormDiv");

    var headingSpan = document.createElement("h2");
    formDiv.appendChild(headingSpan);
    headingSpan.innerHTML = "Policy Editor";

    var form = document.createElement("editPolicyForm");
    formDiv.appendChild(form);

    form.setAttribute("id", "editPolicyForm");
    form.setAttribute("class", "form-style-1");
    form.setAttribute("method", "post");
    form.setAttribute("createEditOrView", createEditOrView);

    var formul = document.createElement("ul");
    form.appendChild(formul);

    // name
    var nameLI = document.createElement("li");
    formul.appendChild(nameLI);
    var nameLabel = document.createElement("label");
    nameLI.appendChild(nameLabel);
    nameLabel.setAttribute("for", "editPolicyFormNameInput");
    nameLabel.innerHTML = "Name: ";
    var nameLabelSpan = document.createElement("span");
    nameLabel.appendChild(nameLabelSpan);
    nameLabelSpan.setAttribute("class", "required");
    nameLabelSpan.innerHTML = "*";
    var nameInput = document.createElement("input");
    nameLI.appendChild(nameInput);
    nameInput.setAttribute("id", "editPolicyFormNameInput");
    nameInput.setAttribute("type", "text");
    nameInput.setAttribute("name", "editPolicyFormNameInput");
    nameInput.setAttribute("class", "field ebInput");
    nameInput.setAttribute("placeholder", "name");
    if (policy != null && policy.policyKey != null && policy.policyKey.name != null) {
        nameInput.value = policy.policyKey.name;
    }
    if (createEditOrView != "CREATE") {
        nameInput.readOnly = true;
    }

    // version
    var versionLI = document.createElement("li");
    formul.appendChild(versionLI);
    var versionLabel = document.createElement("label");
    versionLI.appendChild(versionLabel);
    versionLabel.setAttribute("for", "editPolicyFormVersionInput");
    versionLabel.innerHTML = "Version: ";
    var versionInput = document.createElement("input");
    versionLI.appendChild(versionInput);
    versionInput.setAttribute("id", "editPolicyFormVersionInput");
    versionInput.setAttribute("type", "text");
    versionInput.setAttribute("name", "editPolicyFormVersionInput");
    versionInput.setAttribute("class", "field ebInput");
    versionInput.setAttribute("placeholder", "0.0.1");
    if (policy != null && policy.policyKey != null && policy.policyKey.version != null) {
        versionInput.value = policy.policyKey.version;
    }
    if (createEditOrView != "CREATE") {
        versionInput.readOnly = true;
    }

    // uuid
    var uuidLI = document.createElement("li");
    formul.appendChild(uuidLI);
    var uuidLabel = document.createElement("label");
    uuidLI.appendChild(uuidLabel);
    uuidLabel.setAttribute("for", "editPolicyFormUuidInput");
    uuidLabel.innerHTML = "UUID: ";
    var uuidInput = document.createElement("input");
    uuidLI.appendChild(uuidInput);
    uuidInput.setAttribute("id", "editPolicyFormUuidInput");
    uuidInput.setAttribute("type", "text");
    uuidInput.setAttribute("name", "editPolicyFormUuidInput");
    uuidInput.setAttribute("class", "field-long ebInput ebInput_width_full");
    uuidInput.setAttribute("placeholder", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
    if (policy != null && policy.uuid != null) {
        uuidInput.value = policy.uuid;
    }
    if (createEditOrView != "CREATE") {
        uuidInput.readOnly = true;
    }

    var edit_disabled = (createEditOrView != "CREATE" && createEditOrView != "EDIT");

    // description
    var descriptionLI = document.createElement("li");
    formul.appendChild(descriptionLI);
    var descriptionLabel = document.createElement("label");
    descriptionLI.appendChild(descriptionLabel);
    descriptionLabel.setAttribute("for", "editPolicyFormDescriptionTextArea");
    descriptionLabel.innerHTML = "Description: ";
    var descriptionTextArea = document.createElement("textarea");
    descriptionLI.appendChild(descriptionTextArea);
    descriptionTextArea.setAttribute("id", "editPolicyFormDescriptionTextArea");
    descriptionTextArea.setAttribute("name", "editPolicyFormDescriptionTextArea");
    descriptionTextArea.setAttribute("class", "field-long ebTextArea ebTextArea_width_full");
    if (policy != null && policy.description != null) {
        descriptionTextArea.value = policy.description;
    }
    descriptionTextArea.readOnly = edit_disabled;

    // template type
    var templateTypeLI = document.createElement("li");
    formul.appendChild(templateTypeLI);
    var templateTypeLabel = document.createElement("label");
    templateTypeLI.appendChild(templateTypeLabel);
    templateTypeLabel.setAttribute("for", "editEventFormTemplateTypeInput");
    templateTypeLabel.innerHTML = "Policy Type / Flavour: ";
    var templateTypeInput = document.createElement("input");
    templateTypeLI.appendChild(templateTypeInput);
    templateTypeInput.setAttribute("id", "editEventFormTemplateTypeInput");
    templateTypeInput.setAttribute("type", "text");
    templateTypeInput.setAttribute("name", "editEventFormTemplateTypeInput");
    templateTypeInput.setAttribute("class", "field-policyTemplateType ebInput");
    templateTypeInput.setAttribute("placeholder", "FREEFORM");
    if (policy != null && policy.template != null) {
        templateTypeInput.value = policy.template;
    } else {
        templateTypeInput.value = "FREEFORM";
    }
    if (createEditOrView != "CREATE" && createEditOrView != "EDIT") {
        templateTypeInput.readOnly = true;
    }

    // first state
    var firstStateLI = document.createElement("li");
    formul.appendChild(firstStateLI);
    var firstStateLabel = document.createElement("label");
    firstStateLI.appendChild(firstStateLabel);
    firstStateLabel.setAttribute("for", "editEventFormSelectFirstState_dropdownList");
    firstStateLabel.innerHTML = "First State: ";
    var firststateoptions = new Array();
    var firststateselected = null;
    if (policy != null && policy.state != null) {
        for (let value of policy.state.entry) {
            if (value != null && value.key != null) {
                var statename = value.key;
                firststateoptions.push({
                    "name" : statename,
                    "displaytext" : statename
                });
            }
        }
    }
    if (policy != null && policy.firstState != null && policy.firstState != "") {
        firststateselected = {
            "name" : policy.firstState,
            "displaytext" : policy.firstState
        }
    }
    var firstStateSelectDiv = dropdownList("editEventFormSelectFirstState", firststateoptions, firststateselected,
            (createEditOrView != "CREATE" && createEditOrView != "EDIT"), function() {
                return editPolicyForm_updateTriggerEventOptions(events);
            }, function() {
                return editPolicyForm_getStateOptions();
            });
    firstStateLI.appendChild(firstStateSelectDiv);

    // Trigger event
    var triggerLI = document.createElement("li");
    formul.appendChild(triggerLI);
    var triggerLabel = document.createElement("label");
    triggerLI.appendChild(triggerLabel);
    triggerLabel.setAttribute("for", "editEventFormSelectTrigger_dropdownList");
    triggerLabel.innerHTML = "Policy Trigger Event: ";
    var triggerevent = null;
    if (policy != null && policy.firstState != null && policy.firstState != "" && policy.state != null) {
        for (let entry of policy.state.entry) {
            if (entry != null && entry.key != null) {
                statename = entry.key;
                var state = entry.value;
                if (statename != null && statename == policy.firstState) {
                    triggerevent = {
                        "name" : state.trigger.name,
                        "version" : state.trigger.version,
                        "displaytext" : state.trigger.name + ":" + state.trigger.version
                    };
                }
            }
        }
    }
    // var triggerSelectDiv = dropdownList("editEventFormSelectTrigger", events,
    // triggerevent, true, null); // ewatkmi: replaced dropdown with label
    var triggerSelectDiv = document.createElement("label");
    triggerSelectDiv.setAttribute("class", "policy-trigger-event");
    triggerSelectDiv.setAttribute("id", "editEventFormSelectTrigger_dropdownList");
    triggerSelectDiv.innerHTML = triggerevent ? triggerevent.displaytext : "No Event Selected";
    triggerLI.appendChild(triggerSelectDiv);
    var triggerPeriodicEventCheckbox = document.createElement("input");
    triggerPeriodicEventCheckbox.setAttribute("type", "checkbox");
    triggerPeriodicEventCheckbox.setAttribute("id", "periodicEventsCheckbox");
    triggerPeriodicEventCheckbox.setAttribute("class", "field-checkbox-center periodic-events-checkbox");
    triggerPeriodicEventCheckbox.disabled = createEditOrView != "EDIT";
    triggerPeriodicEventCheckbox.onclick = function() {
        var firstState = document.getElementById("editEventFormSelectFirstState_dropdownList_display").innerHTML;
        var firstStateDropdown = document.getElementById("editPolicyFormTrigger_" + firstState + "_dropdownList");
        if ($(triggerPeriodicEventCheckbox).is(":checked")) {
            var periodicEvent = undefined;
            var tmpEvents = $.merge([], events);
            for ( var e in events) {
                if (events[e].name.indexOf("PeriodicEvent") !== -1) {
                    periodicEvent = events[e];
                    break;
                }
            }
            if (!periodicEvent) {
                periodicEvent = {
                    name : "PeriodicEvent",
                    version : "0.0.1",
                    displaytext : "PeriodicEvent:0.0.1",
                    event : {
                        description : "",
                        key : {
                            name : "PeriodicEvent",
                            version : "0.0.1"
                        },
                        nameSpace : "org.onap.policy.apex.domains.aadm.events",
                        parameter : {
                            entry : [ {
                                key : "PERIODIC_EVENT_COUNT",
                                value : {
                                    key : "PERIODIC_EVENT_COUNT",
                                    optional : false,
                                    fieldSchemaKey : {
                                        name : "PeriodicEventCount",
                                        version : "0.0.1"
                                    }
                                }
                            } ]
                        },
                        source : "System",
                        target : "Apex",
                        uuid : "44236da1-3d47-4988-8033-b6fee9d6a0f4"
                    },
                };
                tmpEvents.push(periodicEvent);
            }

            dropdownList_ChangeOptions(firstStateDropdown, tmpEvents, periodicEvent, false);
            editPolicyForm_updateTriggerEventOptions(tmpEvents);
        } else {
            dropdownList_ChangeOptions(firstStateDropdown, events, events[0], false);
            editPolicyForm_updateTriggerEventOptions(events);
        }
    }

    triggerLI.appendChild(triggerPeriodicEventCheckbox);

    var triggerPeriodicEventLabel = document.createElement("label");
    triggerPeriodicEventLabel.setAttribute("class", "periodic-events-label");
    triggerPeriodicEventLabel.innerHTML = "is Periodic Event";
    triggerLI.appendChild(triggerPeriodicEventLabel);

    // states
    var statesLI = document.createElement("li");
    formul.appendChild(statesLI);
    var statesLabel = document.createElement("label");
    statesLI.appendChild(statesLabel);
    statesLabel.setAttribute("for", "editEventFormStates");
    statesLabel.innerHTML = "States: ";
    var statesUL = document.createElement("ul");
    statesUL.setAttribute("id", "editEventFormStates");
    statesLI.appendChild(statesUL);
    if (policy && policy.state) {
        var states = policy.state.entry;
        for ( var s in states) {
            state = states[s];
            if (state.key == policy.firstState) {
                states.splice(s, 1);
                states.unshift(state);
                break;
            }
        }
        for (i = 0; i < policy.state.entry.length; i++) {
            var stateEntry = policy.state.entry[i];
            statename = stateEntry.key;
            state = stateEntry.value;
            var stateLI = editPolicyForm_addState(statename, state, createEditOrView, policy, tasks, events,
                    contextAlbums, contextItemSchemas);
            statesUL.appendChild(stateLI);
        }
    }

    // add new state
    if (createEditOrView == "CREATE" || createEditOrView == "EDIT") {
        var newStateLI = document.createElement("li");
        statesUL.appendChild(newStateLI);
        var newStateLabel = document.createElement("label");
        newStateLI.appendChild(newStateLabel);
        newStateLabel.setAttribute("for", "editPolicyFormStateDiv_");
        newStateLabel.innerHTML = "Add a new State: ";
        var newStDiv = document.createElement("div");
        newStateLI.appendChild(newStDiv);
        newStDiv.setAttribute("id", "editPolicyFormStateDiv_");
        newStDiv.setAttribute("class", "editPolicyFormStateDiv");
        var newStateInput = document.createElement("input");
        newStDiv.appendChild(newStateInput);
        newStateInput.setAttribute("id", "editEventFormNewStateInput");
        newStateInput.setAttribute("type", "text");
        newStateInput.setAttribute("name", "editEventFormTemplateTypeInput");
        newStateInput.setAttribute("class", "field-policyTemplateType ebInput ebInput_width_xLong");
        newStateInput.setAttribute("placeholder", "Name for new State ... ");
        var addState = document.createElement("button");
        newStDiv.appendChild(addState);
        addState.setAttribute("id", "addStateButton");
        addState.setAttribute("class", "ebBtn");
        addState.setAttribute("type", "submit");
        addState.setAttribute("value", "Add a new State");
        addState.style["margin-left"] = "10px";
        addState.onclick = function() {
            return editPolicyForm_addNewState(statesUL, createEditOrView, policy, tasks, events, contextAlbums,
                    contextItemSchemas);
        };
        addState.innerHTML = addState.getAttribute("value");
    }

    // buttons
    var inputLI = document.createElement("li");
    formul.appendChild(inputLI);
    if (createEditOrView == "CREATE") {
        var generateUUIDInput = document.createElement("button");
        inputLI.appendChild(generateUUIDInput);
        generateUUIDInput.setAttribute("id", "generateUUID");
        generateUUIDInput.setAttribute("class", "ebBtn ebBtn_large");
        generateUUIDInput.setAttribute("type", "submit");
        generateUUIDInput.setAttribute("value", "Generate UUID");
        generateUUIDInput.onclick = editPolicyForm_generateUUIDPressed;
        generateUUIDInput.innerHTML = generateUUIDInput.getAttribute("value");

        var inputSpan0 = document.createElement("span");
        inputLI.appendChild(inputSpan0);
        inputSpan0.setAttribute("class", "required");
        inputSpan0.innerHTML = " ";

        var generateDescriptionInput = document.createElement("button");
        inputLI.appendChild(generateDescriptionInput);
        generateDescriptionInput.setAttribute("id", "generateDescription");
        generateDescriptionInput.setAttribute("class", "ebBtn ebBtn_large");
        generateDescriptionInput.setAttribute("type", "submit");
        generateDescriptionInput.setAttribute("value", "Generate Description");
        generateDescriptionInput.onclick = editPolicyForm_generateDescriptionPressed;
        generateDescriptionInput.innerHTML = generateDescriptionInput.getAttribute("value");

        var inputSpan1 = document.createElement("span");
        inputLI.appendChild(inputSpan1);
        inputSpan1.setAttribute("class", "required");
        inputSpan1.innerHTML = " ";
    }

    var cancelInput = document.createElement("button");
    inputLI.appendChild(cancelInput);
    cancelInput.setAttribute("id", "cancel");
    cancelInput.setAttribute("class", "ebBtn ebBtn_large");
    cancelInput.setAttribute("type", "submit");
    cancelInput.setAttribute("value", "Cancel");
    cancelInput.onclick = editPolicyForm_cancelPressed;
    cancelInput.innerHTML = cancelInput.getAttribute("value");

    if (createEditOrView == "CREATE" || createEditOrView == "EDIT") {
        var inputSpan2 = document.createElement("span");
        inputLI.appendChild(inputSpan2);
        inputSpan2.setAttribute("class", "required");
        inputSpan2.innerHTML = " ";
        var submitInput = document.createElement("button");
        inputLI.appendChild(submitInput);
        submitInput.setAttribute("id", "submit");
        submitInput.setAttribute("class", "ebBtn ebBtn_large");
        submitInput.setAttribute("type", "submit");
        submitInput.setAttribute("value", "Submit");
        submitInput.onclick = editPolicyForm_submitPressed;
        submitInput.innerHTML = submitInput.getAttribute("value");
    }

    formParent.appendChild(contentelement);
    scrollToTop();
}

function editPolicyForm_addNewState(statesUL, createEditOrView, policy, tasks, events, contextAlbums,
        contextItemSchemas) {
    var statename = document.getElementById("editEventFormNewStateInput").value;
    if (statename == null || statename == "") {
        alert("Please enter a value for the name of the new state\"" + paramname + "\"");
        document.getElementById("editEventFormNewStateInput").focus();
        return false;
    } else if (statename.toUpperCase() == "NULL" || statename.toUpperCase() == "NONE") {
        alert("Please enter a valid value for the name of the new state\"" + paramname
                + "\". Values \"NULL\" and \"None\" are not allowed");
        document.getElementById("editEventFormNewStateInput").focus();
        return false;
    } else {
        document.getElementById("editEventFormNewStateInput").value = "";
    }
    if (policy && policy.state) {
        for (let value of policy.state.entry) {
            if (statename.toUpperCase() == value.key.toUpperCase()) {
                alert("Policy " + policy.policyKey.name + ":" + policy.policyKey.version
                        + " already contains a state called \"" + statename + "\".");
                document.getElementById("editEventFormNewStateInput").focus();
                return false;
            }
        }
    }
    var stateLI = editPolicyForm_addState(statename, null, createEditOrView, policy, tasks, events, contextAlbums,
            contextItemSchemas);
    statesUL.insertBefore(stateLI, statesUL.lastElementChild);
    editPolicyForm_updateTriggerEventOptions(events);
}

function editPolicyForm_getStateOptions() {
    var stateoptions = new Array();
    var stateslis = document.getElementById("editEventFormStates").querySelectorAll(
            "#editEventFormStates > li[stateName]"); // get li direct child
                                                        // elements with an
                                                        // attribute "stateName"
    for (let value of stateslis) {
        if (stateslis != null && value != null && value.getAttribute("stateName") != null) {
            stateoptions.push({
                "name" : value.getAttribute("stateName"),
                "displaytext" : value.getAttribute("stateName")
            });
        }
    }
    return stateoptions;
}

function editPolicyForm_getNextStateOptions() {
    var stateoptions = editPolicyForm_getStateOptions();
    stateoptions.push({
        "name" : "NULL",
        "displaytext" : "None"
    });
    return stateoptions;
}

function editPolicyForm_updateTriggerEventOptions(events) {
    var stateevent = null;
    var triggerSelectDiv = document.getElementById("editEventFormSelectTrigger_dropdownList");
    var firstStateSelectDiv = document.getElementById("editEventFormSelectFirstState_dropdownList");
    var firststate = firstStateSelectDiv.selectedOption;
    var createEditOrView = document.getElementById("editPolicyForm").getAttribute("createEditOrView");
    if (firststate != null && firststate.name != null) {
        var statename = firststate.name;
        var stateeventselect = document.getElementById("editPolicyFormTrigger_" + statename + "_dropdownList");
        if (stateeventselect != null && stateeventselect.selectedOption) {
            stateevent = stateeventselect.selectedOption;
        }
        if (createEditOrView == "CREATE") {
            var periodicCheckbox = document.getElementById("periodicEventsCheckbox");
            if (periodicCheckbox.hasAttribute("disabled")) {
                periodicCheckbox.removeAttribute("disabled");
            }
        }
    } else {
        triggerSelectDiv = document.getElementById("editEventFormSelectTrigger_dropdownList");
        triggerSelectDiv.innerHTML = "No Event Selected";
        var periodicEventsCheckbox = $("#periodicEventsCheckbox");
        if (periodicEventsCheckbox.is(":checked")) {
            periodicEventsCheckbox.attr("checked", false);
        }
        if (createEditOrView == "CREATE") {
            periodicCheckbox = document.getElementById("periodicEventsCheckbox");
            if (!periodicCheckbox.hasAttribute("disabled")) {
                periodicCheckbox.disabled = true;
            }
        }
    }
    if (stateevent) {
        triggerSelectDiv.innerHTML = stateevent.displaytext;
        if (stateevent.displaytext.indexOf("PeriodicEvent") == -1) {
            periodicEventsCheckbox = $("#periodicEventsCheckbox");
            if (periodicEventsCheckbox.is(":checked")) {
                periodicEventsCheckbox.attr("checked", false);
            }
        }
    }
}

function editPolicyForm_addState(statename, state, createEditOrView, policy, tasks, events, contextAlbums,
        contextItemSchemas) {
    var stateLI = document.createElement("li");
    stateLI.setAttribute("stateName", statename);
    var deleteDiv = document.createElement("div");
    if (createEditOrView == "CREATE" || createEditOrView == "EDIT") {
        deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete");
        deleteDiv.onclick = function(event) {
            $(stateLI)
                    .hide(
                            "fast",
                            function() {
                                stateLI.parentNode.removeChild(stateLI);
                                var firstState = document
                                        .getElementById("editEventFormSelectFirstState_dropdownList_display").innerHTML;
                                var selected = (statename !== firstState) ? {
                                    name : firstState,
                                    displaytext : firstState
                                } : undefined;
                                dropdownList_ChangeOptions(document
                                        .getElementById("editEventFormSelectFirstState_dropdownList"),
                                        editPolicyForm_getStateOptions(), selected, false,
                                        editPolicyForm_getStateOptions);
                                editPolicyForm_updateTriggerEventOptions();
                            });
        }
    } else {
        deleteDiv.setAttribute("class", "ebIcon ebIcon_interactive ebIcon_delete ebIcon_disabled");
    }
    deleteDiv.style["vertical-align"] = "baseline";
    stateLI.appendChild(deleteDiv);
    var stateLabel = document.createElement("label");
    stateLabel.style.display = "inline-block";
    stateLabel.style["min-width"] = "120px";
    stateLabel.style["padding-left"] = "10px";
    stateLabel.style["vertical-align"] = "middle";
    stateLabel.innerHTML = statename;
    stateLI.appendChild(stateLabel);
    var stateDiv = editPolicyForm_State_generateStateDiv(createEditOrView, policy, statename, state, tasks, events,
            contextAlbums, contextItemSchemas);
    var showhideDIV = showHideElement("editEventFormStates_" + statename, stateDiv, true, "Show " + statename + " ...",
            "Hide " + statename + " ...", "showhide_div_show", "showhide_div_hide", "showhide_button_show",
            "showhide_button_hide");
    showhideDIV.style.display = "inline-block";
    showhideDIV.style["vertical-align"] = "middle";
    stateLabel.setAttribute("for", stateDiv.id);
    stateLI.appendChild(showhideDIV);
    stateLI.appendChild(stateDiv);
    return stateLI;
}

function editPolicyForm_generateUUIDPressed() {
    document.getElementById("editPolicyFormUuidInput").value = formUtils_generateUUID();
}

function editPolicyForm_generateDescriptionPressed() {
    document.getElementById("editPolicyFormDescriptionTextArea").value = formUtils_generateDescription(document
            .getElementById("editPolicyFormNameInput").value,
            document.getElementById("editPolicyFormVersionInput").value, document
                    .getElementById("editPolicyFormUuidInput").value);
}

function editPolicyForm_cancelPressed() {
    apexUtils_removeElement("editPolicyFormDiv");
    policyTab_reset();
}

function editPolicyForm_submitPressed() {
    var createEditOrView = document.getElementById("editPolicyForm").getAttribute("createEditOrView");
    if (!createEditOrView || createEditOrView == "" || (createEditOrView != "CREATE" && createEditOrView != "EDIT")) {
        console.error("Invalid operation \"" + createEditOrView
                + "\" passed to editPolicyForm_submitPressed function. Edit failed");
        apexUtils_removeElement("editPolicyFormDiv");
        policyTab_reset();
        return;
    }

    var policybean = editPolicyForm_getPolicyBean();
    if (policybean == null) {
        return false;
    }
    var jsonString = JSON.stringify(policybean);

    if (createEditOrView == "CREATE") {
        var requestURL = window.restRootURL + "/Policy/Create";
        ajax_post(requestURL, jsonString, function(resultData) {
            apexUtils_removeElement("editPolicyFormDiv");
            policyTab_reset();
            keyInformationTab_reset();
        });
    } else if (createEditOrView == "EDIT") {
        var firstStatePeriodic = $("#periodicEventsCheckbox").is(":checked")
        requestURL = window.restRootURL + "/Policy/Update?firstStatePeriodic=" + firstStatePeriodic;
        ajax_put(requestURL, jsonString, function(resultData) {
            apexUtils_removeElement("editPolicyFormDiv");
            policyTab_reset();
            keyInformationTab_reset();
        });
    }

}

function editPolicyForm_getPolicyBean() {

    var name = document.getElementById('editPolicyFormNameInput').value;
    if (name == null || name == "") {
        console.error("No Name is specified for the policy");
        alert("No Name is specified for the policy");
        return null;
    }
    var version = document.getElementById('editPolicyFormVersionInput').value;
    if (version == null || version == "") {
        console.error("No Version is specified for the policy");
        alert("No Version is specified for the policy");
        return null;
    }
    var uuid = document.getElementById('editPolicyFormUuidInput').value;
    if (uuid == null || uuid == "") {
        console.error("No UUID is specified for the policy");
        alert("No UUID is specified for the policy");
        return null;
    }
    var desc = document.getElementById('editPolicyFormDescriptionTextArea').value;
    if (desc == null) {
        desc = "";
    }
    var template = document.getElementById('editEventFormTemplateTypeInput').value;
    if (template == null) {
        template = "";
    }
    var firststateselectedoption = document.getElementById("editEventFormSelectFirstState" + "_dropdownList").selectedOption;
    if (firststateselectedoption == null) {
        console.error("Please select an option for First State");
        alert("Please select an option for First State");
        return null;
    }
    var states = new Object();
    var stateslis = document.getElementById("editEventFormStates").querySelectorAll(
            "#editEventFormStates > li[stateName]"); // get li direct child
                                                        // elements with an
                                                        // attribute "stateName"
    for (let value of stateslis) { // ignore last li ... it has
                                                    // the new state button etc.
        if (stateslis != null && value != null && value.getAttribute("stateName") != null) {
            var statename = value.getAttribute("stateName");
            var state = editPolicyForm_State_getStateBean(statename);
            if (state == null) {
                return null;
            }
            states[statename] = state;
        }
    }

    return {
        "name" : name,
        "version" : version,
        "uuid" : uuid,
        "description" : desc,
        "template" : template,
        "firstState" : firststateselectedoption.name,
        "states" : states
    };
}

export {
    editPolicyForm_activate,
    editPolicyForm_editPolicy_inner,
    editPolicyForm_State_getStateBean,
    editPolicyForm_addNewState,
    editPolicyForm_addState,
    editPolicyForm_cancelPressed,
    editPolicyForm_createPolicy,
    editPolicyForm_deletePolicy,
    editPolicyForm_editPolicy,
    editPolicyForm_generateDescriptionPressed,
    editPolicyForm_generateUUIDPressed,
    editPolicyForm_getNextStateOptions,
    editPolicyForm_getPolicyBean,
    editPolicyForm_getStateOptions,
    editPolicyForm_State_generateStateDiv,
    editPolicyForm_submitPressed,
    editPolicyForm_updateTriggerEventOptions,
    editPolicyForm_viewPolicy
}