// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
(function(cloudStack, $) {
    cloudStack.sections.templates = {
        title: 'label.menu.templates',
        id: 'templates',
        sectionSelect: {
            label: 'label.select-view'
        },
        sections: {
            templates: {
                type: 'select',
                title: 'label.menu.templates',
                listView: {
                    id: 'templates',
                    label: 'label.menu.templates',
                    filters: {
                        all: {
                            preFilter: function(args) {
                                if (isAdmin()) //"listTemplates&templatefilter=all" only works for root-admin, but no domain-admin. Domain-admin is unable to see all templates until listTemplates API supports a new type of templatefilter for domain-admin to see all templates in his domain.
                                    return true;
                                else
                                    return false;
                            },
                            label: 'ui.listView.filters.all'
                        },
                        mine: {
                            label: 'ui.listView.filters.mine'
                        },
                        featured: {
                            label: 'label.featured'
                        },
                        community: {
                            label: 'label.community'
                        }
                    },
                    fields: {
                        name: {
                            label: 'label.name'
                        },
                        zonename: {
                            label: 'label.zone'
                        },
                        hypervisor: {
                            label: 'label.hypervisor'
                        }
                    },
                    advSearchFields: {
                        name: {
                            label: 'Name'
                        },
                        zoneid: {
                            label: 'Zone',
                            select: function(args) {
                                $.ajax({
                                    url: createURL('listZones'),
                                    data: {
                                        listAll: true
                                    },
                                    success: function(json) {
                                        var zones = json.listzonesresponse.zone ? json.listzonesresponse.zone : [];
                                        args.response.success({
                                            data: $.map(zones, function(zone) {
                                                return {
                                                    id: zone.id,
                                                    description: zone.name
                                                };
                                            })
                                        });
                                    }
                                });
                            }
                        },
                        tagKey: {
                            label: 'Tag Key'
                        },
                        tagValue: {
                            label: 'Tag Value'
                        }
                    },
                    reorder: cloudStack.api.actions.sort('updateTemplate', 'templates'),
                    actions: {
                        add: {
                            label: 'label.action.register.template',
                            messages: {
                                notification: function(args) {
                                    return 'label.action.register.template';
                                }
                            },
                            createForm: {
                                title: 'label.action.register.template',
                                docID: 'helpNetworkOfferingName',
                                preFilter: cloudStack.preFilter.createTemplate,
                                fields: {
                                    name: {
                                        label: 'label.name',
                                        docID: 'helpRegisterTemplateName',
                                        validation: {
                                            required: true
                                        }
                                    },
                                    description: {
                                        label: 'label.description',
                                        docID: 'helpRegisterTemplateDescription',
                                        validation: {
                                            required: true
                                        }
                                    },
                                    url: {
                                        label: 'URL',
                                        docID: 'helpRegisterTemplateURL',
                                        validation: {
                                            required: true
                                        }
                                    },
                                    zone: {
                                        label: 'label.zone',
                                        docID: 'helpRegisterTemplateZone',
                                        select: function(args) {
                                            $.ajax({
                                                url: createURL("listZones&available=true"),
                                                dataType: "json",
                                                async: true,
                                                success: function(json) {
                                                    var zoneObjs = [];
                                                    var items = json.listzonesresponse.zone;
                                                    if (items != null) {
                                                        for (var i = 0; i < items.length; i++) {
                                                            zoneObjs.push({
                                                                id: items[i].id,
                                                                description: items[i].name
                                                            });
                                                        }
                                                    }
                                                    if (isAdmin() && !(cloudStack.context.projects && cloudStack.context.projects[0])) {
                                                        zoneObjs.unshift({
                                                            id: -1,
                                                            description: "All Zones"
                                                        });
                                                    }
                                                    args.response.success({
                                                        data: zoneObjs
                                                    });
                                                }
                                            });
                                        }
                                    },
                                    hypervisor: {
                                        label: 'label.hypervisor',
                                        docID: 'helpRegisterTemplateHypervisor',
                                        dependsOn: 'zone',
                                        select: function(args) {
                                            if (args.zone == null)
                                                return;
                                            var apiCmd;
                                            if (args.zone == -1)
                                                apiCmd = "listHypervisors&zoneid=-1";
                                            else
                                                apiCmd = "listHypervisors&zoneid=" + args.zone;
                                            $.ajax({
                                                url: createURL(apiCmd),
                                                dataType: "json",
                                                async: false,
                                                success: function(json) {
                                                    var hypervisorObjs = json.listhypervisorsresponse.hypervisor;
                                                    var items = [];
                                                    $(hypervisorObjs).each(function() {
                                                        items.push({
                                                            id: this.name,
                                                            description: this.name
                                                        });
                                                    });
                                                    args.response.success({
                                                        data: items
                                                    });
                                                }
                                            });
                                            args.$select.change(function() {
                                                var $form = $(this).closest('form');
                                                if ($(this).val() == "VMware") {
                                                    $form.find('.form-item[rel=rootDiskControllerType]').css('display', 'inline-block');
                                                    $form.find('.form-item[rel=nicAdapterType]').css('display', 'inline-block');
                                                    $form.find('.form-item[rel=keyboardType]').css('display', 'inline-block');
                                                } else {
                                                    $form.find('.form-item[rel=rootDiskControllerType]').hide();
                                                    $form.find('.form-item[rel=nicAdapterType]').hide();
                                                    $form.find('.form-item[rel=keyboardType]').hide();
                                                }
                                            });
                                        }
                                    },
                                    //fields for hypervisor == "VMware" (starts here)
                                    rootDiskControllerType: {
                                        label: 'label.root.disk.controller',
                                        isHidden: true,
                                        select: function(args) {
                                            var items = []
                                            items.push({
                                                id: "",
                                                description: ""
                                            });
                                            items.push({
                                                id: "scsi",
                                                description: "scsi"
                                            });
                                            items.push({
                                                id: "ide",
                                                description: "ide"
                                            });
                                            args.response.success({
                                                data: items
                                            });
                                        }
                                    },
                                    nicAdapterType: {
                                        label: 'label.nic.adapter.type',
                                        isHidden: true,
                                        select: function(args) {
                                            var items = []
                                            items.push({
                                                id: "",
                                                description: ""
                                            });
                                            items.push({
                                                id: "E1000",
                                                description: "E1000"
                                            });
                                            items.push({
                                                id: "PCNet32",
                                                description: "PCNet32"
                                            });
                                            items.push({
                                                id: "Vmxnet2",
                                                description: "Vmxnet2"
                                            });
                                            items.push({
                                                id: "Vmxnet3",
                                                description: "Vmxnet3"
                                            });
                                            args.response.success({
                                                data: items
                                            });
                                        }
                                    },
                                    keyboardType: {
                                        label: 'label.keyboard.type',
                                        isHidden: true,
                                        select: function(args) {
                                            var items = []
                                            items.push({
                                                id: "",
                                                description: ""
                                            });
                                            items.push({
                                                id: "us",
                                                description: "US"
                                            });
                                            items.push({
                                                id: "jp",
                                                description: "Japanese"
                                            });
                                            args.response.success({
                                                data: items
                                            });
                                        }
                                    },
                                    //fields for hypervisor == "VMware" (ends here)
                                    format: {
                                        label: 'label.format',
                                        docID: 'helpRegisterTemplateFormat',
                                        dependsOn: 'hypervisor',
                                        select: function(args) {
                                            var items = [];
                                            if (args.hypervisor == "XenServer") {
                                                //formatSelect.append("");
                                                items.push({
                                                    id: 'VHD',
                                                    description: 'VHD'
                                                });
                                            } else if (args.hypervisor == "VMware") {
                                                //formatSelect.append("");
                                                items.push({
                                                    id: 'OVA',
                                                    description: 'OVA'
                                                });
                                            } else if (args.hypervisor == "KVM") {
                                                //formatSelect.append("");
                                                items.push({
                                                    id: 'QCOW2',
                                                    description: 'QCOW2'
                                                });
                                            } else if (args.hypervisor == "BareMetal") {
                                                //formatSelect.append("");
                                                items.push({
                                                    id: 'BareMetal',
                                                    description: 'BareMetal'
                                                });
                                            } else if (args.hypervisor == "Ovm") {
                                                //formatSelect.append("");
                                                items.push({
                                                    id: 'RAW',
                                                    description: 'RAW'
                                                });
                                            } else if (args.hypervisor == "LXC") {
                                                //formatSelect.append("");
                                                items.push({
                                                    id: 'TAR',
                                                    description: 'TAR'
                                                });
                                            }
                                            args.response.success({
                                                data: items
                                            });
                                        }
                                    },
                                    osTypeId: {
                                        label: 'label.os.type',
                                        docID: 'helpRegisterTemplateOSType',
                                        select: function(args) {
                                            $.ajax({
                                                url: createURL("listOsTypes"),
                                                dataType: "json",
                                                async: true,
                                                success: function(json) {
                                                    var items = json.listostypesresponse.ostype;
                                                    args.response.success({
                                                        data: items
                                                    });
                                                }
                                            });
                                        }
                                    },
                                    isExtractable: {
                                        label: "extractable",
                                        docID: 'helpRegisterTemplateExtractable',
                                        isBoolean: true
                                    },
                                    isPasswordEnabled: {
                                        label: "label.password.enabled",
                                        docID: 'helpRegisterTemplatePasswordEnabled',
                                        isBoolean: true
                                    },
                                    isdynamicallyscalable: {
                                        label: "Dynamically Scalable",
                                        isBoolean: true
                                    },
                                    isPublic: {
                                        label: "label.public",
                                        docID: 'helpRegisterTemplatePublic',
                                        isBoolean: true,
                                        isHidden: true
                                    },
                                    isFeatured: {
                                        label: "label.featured",
                                        docID: 'helpRegisterTemplateFeatured',
                                        isBoolean: true,
                                        isHidden: true
                                    }
                                }
                            },
                            action: function(args) {
                                var data = {
                                    name: args.data.name,
                                    displayText: args.data.description,
                                    url: args.data.url,
                                    zoneid: args.data.zone,
                                    format: args.data.format,
                                    isextractable: (args.data.isExtractable == "on"),
                                    passwordEnabled: (args.data.isPasswordEnabled == "on"),
                                    isdynamicallyscalable: (args.data.isdynamicallyscalable == "on"),
                                    osTypeId: args.data.osTypeId,
                                    hypervisor: args.data.hypervisor
                                };
                                if (args.$form.find('.form-item[rel=isPublic]').css("display") != "none") {
                                    $.extend(data, {
                                        ispublic: (args.data.isPublic == "on")
                                    });
                                }
                                if (args.$form.find('.form-item[rel=isFeatured]').css("display") != "none") {
                                    $.extend(data, {
                                        isfeatured: (args.data.isFeatured == "on")
                                    });
                                }
                                //VMware only (starts here)
                                if (args.$form.find('.form-item[rel=rootDiskControllerType]').css("display") != "none" && args.data.rootDiskControllerType != "") {
                                    $.extend(data, {
                                        'details[0].rootDiskController': args.data.rootDiskControllerType
                                    });
                                }
                                if (args.$form.find('.form-item[rel=nicAdapterType]').css("display") != "none" && args.data.nicAdapterType != "") {
                                    $.extend(data, {
                                        'details[0].nicAdapter': args.data.nicAdapterType
                                    });
                                }
                                if (args.$form.find('.form-item[rel=keyboardType]').css("display") != "none" && args.data.keyboardType != "") {
                                    $.extend(data, {
                                        'details[0].keyboard': args.data.keyboardType
                                    });
                                }
                                //VMware only (ends here)
                                $.ajax({
                                    url: createURL('registerTemplate'),
                                    data: data,
                                    success: function(json) {
                                        var items = json.registertemplateresponse.template; //items might have more than one array element if it's create templates for all zones.
                                        args.response.success({
                                            data: items[0]
                                        });
                                        /*
                     if(items.length > 1) {
                     for(var i=1; i 1) {
                     for(var i=1; i