WIM handler

Change-Id: I4e9f120d9dc8485db850461bb5eb2d0f66bea3d3
Signed-off-by: lombardofr <lombardo@everyup.it>
diff --git a/wimhandler/__init__.py b/wimhandler/__init__.py
new file mode 100644
index 0000000..00de7ab
--- /dev/null
+++ b/wimhandler/__init__.py
@@ -0,0 +1,13 @@
+#   Copyright 2018 EveryUP Srl
+#
+#   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  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.
\ No newline at end of file
diff --git a/wimhandler/apps.py b/wimhandler/apps.py
new file mode 100644
index 0000000..8d17b0a
--- /dev/null
+++ b/wimhandler/apps.py
@@ -0,0 +1,21 @@
+#   Copyright 2018 EveryUP Srl
+#
+#   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  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.
+
+from __future__ import unicode_literals
+
+from django.apps import AppConfig
+
+
+class WimhandlerConfig(AppConfig):
+    name = 'wimhandler'
diff --git a/wimhandler/template/modal/wim_create.html b/wimhandler/template/modal/wim_create.html
new file mode 100644
index 0000000..e7eb6a2
--- /dev/null
+++ b/wimhandler/template/modal/wim_create.html
@@ -0,0 +1,74 @@
+<div class="modal" id="modal_new_wim" xmlns="http://www.w3.org/1999/html">
+    <div class="modal-dialog modal-lg">
+        <div class="modal-content">
+            <div class="modal-header">
+                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+                    <span aria-hidden="true">×</span></button>
+                <h4 class="modal-title">New WIM</h4>
+            </div>
+            <form id="formCreateWIM" action='{% url "wims:create" %}'
+                  class="form-horizontal"
+                  method="post" enctype="multipart/form-data">
+                {% csrf_token %}
+                <div class="modal-body" id="modal_new_wim_body">
+                    <div class="form-group">
+                        <label for="wim_name" class="col-sm-2">Name *</label>
+                        <div class="col-sm-3">
+                            <input class="form-control" id="wim_name" name="name" placeholder="Name" required>
+                        </div>
+
+                        <label for="wim_type" class="col-sm-2">Type *</label>
+                        <div class="col-sm-3">
+                            <select id="wim_type" name="wim_type" class="form-control">
+                                <option value="onos">Onos</option>
+                                <option value="tapi">Tapi</option>
+                                <option value="odl">OpenDaylight</option>
+                                <option value="dynpac">DynPac</option>
+                            </select>
+                        </div>
+                    </div> 
+
+                    <div class="form-group">
+                        <label for="wim_url" class="col-sm-2">URL*</label>
+                        <div class="col-sm-3">
+                            <input type="url" class="form-control" id="wim_url" name="wim_url"
+                                           placeholder="WIM URL" required>
+                        </div>
+                        <label for="wim_user" class="col-sm-2">Username*</label>
+                        <div class="col-sm-3">
+                            <input class="form-control" id="wim_user" name="user"
+                                            placeholder="WIM Username" required>
+                        </div>
+                    </div>
+
+                    <div class="form-group">
+                        <label for="wim_password" class="col-sm-2">Password*</label>
+                        <div class="col-sm-3">
+                            <input type="password" class="form-control" id="wim_password"
+                                       name="password" placeholder="WIMPassword" required>
+                        </div>
+                        <label for="wim_description" class="col-sm-2">Description</label>
+                        <div class="col-sm-3">
+                            <input class="form-control" id="wim_description" name="description"
+                                        placeholder="Description" >
+                        </div>
+                    </div>
+
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancel</button>
+                    <button class="btn btn-primary"
+                            data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Creating..."
+                            id="create_new_wim">Create
+                    </button>
+
+                </div>
+            </form>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
+
+
+
diff --git a/wimhandler/template/modal/wim_details.html b/wimhandler/template/modal/wim_details.html
new file mode 100644
index 0000000..3e788ad
--- /dev/null
+++ b/wimhandler/template/modal/wim_details.html
@@ -0,0 +1,51 @@
+<div class="modal" id="modal_show_wim" xmlns="http://www.w3.org/1999/html">
+    <div class="modal-dialog">
+        <div class="modal-content">
+            <div class="modal-header">
+                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+                    <span aria-hidden="true">×</span></button>
+                <h4 class="modal-title" >WIM Details</h4>
+            </div>
+
+            <div class="modal-body" id="modal_show_wim_body">
+                <div class="row">
+                    <div class="col-lg-10">
+                        <ul class="nav nav-stacked">
+                            <li><a><b>ID:</b> <span id="_id" class="pull-right"></span></a></li>
+                        </ul>
+                    </div>
+                    <div class="col-lg-7">
+                        <ul class="nav nav-stacked">
+                            <li><a><b>Operational State:</b><span id="operationalState" class="pull-right badge"></span></a></li>
+                            <li><a><b> Name:</b><span id="name" class="pull-right"></span></a></li>
+                            <li><a><b>URL:</b><span id="wim_url" class="pull-right "></span></a></li>
+                            <li><a><b>Created:</b><span id="created" class="pull-right "></span></a></li>
+
+                        </ul>
+                    </div>
+                    <div class="col-lg-5">
+                        <ul class="nav nav-stacked">
+                            <li><a><b>Schema Version:</b><span id="schema_version" class="pull-right "></span></a></li>
+                            <li><a><b>Type:</b><span id="wim_type" class="pull-right"></span></a></li>
+                            <li><a><b>Description:</b><span id="description" class="pull-right "></span></a></li>
+                            <li><a><b>Modified:</b><span id="modified" class="pull-right "></span></a></li>
+                        </ul>
+                    </div>
+                    <div class="col-lg-12">
+                        <ul class="nav nav-stacked">
+                        
+                        <li><a><b>Deployed:</b><span id="deployed" class="pull-right "></span></a></li>
+                        <li><a><b>Detailed Status:</b><span id="detailed-status" class="pull-right "></span></a></li>
+                        </ul>
+
+                    </div>
+                </div>
+            </div>
+            <div class="modal-footer">
+                <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
+            </div>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
\ No newline at end of file
diff --git a/wimhandler/template/wim_list.html b/wimhandler/template/wim_list.html
new file mode 100644
index 0000000..9a07c0f
--- /dev/null
+++ b/wimhandler/template/wim_list.html
@@ -0,0 +1,231 @@
+{% extends "base.html" %}
+{% load get %}
+{% load staticfiles %}
+
+
+{% block head_block %}
+    {{ block.super }}
+    <link rel="stylesheet" href="/static/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
+{% endblock %}
+{% block title_header_big %}
+    {{ block.super }}
+{% endblock %}
+{% block left_sidebar %}
+
+   {% include 'osm/osm_project_left_sidebar.html' %}
+
+{% endblock %}
+
+
+{% block breadcrumb_body %}
+    {{ block.super }}
+    <li><a href="{% url "wims:list"   %}">VIMS</a></li>
+{% endblock %}
+
+{% block content_body %}
+    {{ block.super }}
+    {% include 'modal/wim_details.html' %}
+    {% include 'modal/wim_create.html' %}
+    {% csrf_token %}
+    <div class="row">
+        <div class="col-md-12">
+
+            <div class="box">
+                <div class="box-header with-border">
+                    <h3 class="box-title">Registered WIM</h3>
+                    <div class="box-tools">
+                        <button type="button" class="btn btn-default" data-container="body"
+                            data-toggle="tooltip" data-placement="top" title="New PDU"
+                            onclick="javascript:openModalCreateWIM()">
+                        <i class="fa fa-plus"></i> <span> New WIM</span>
+                        </button>
+                    </div>
+                </div>
+                <div class="box-body">
+                    <table id="wims_table" class="table table-bordered table-striped">
+                        <thead>
+                        <tr>
+                            <th>Name</th>
+                            <th>Identifier</th>
+                            <th>Type</th>
+                            <th>Operational State</th>
+                            <th>Description</th>
+                            <th>Actions</th>
+                        </tr>
+                        </thead>
+                        <tbody>
+
+                        </tbody>
+                    </table>
+                </div>
+            </div>
+        </div>
+
+    </div>
+{% endblock %}
+
+{% block resource_block %}
+    {{ block.super }}
+    <script src="/static/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
+    <script src="/static/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
+    <script>
+    $(document).ready( function () {
+        var table = $('#wims_table').DataTable({
+            responsive: true,
+            "ajax": {
+                "url": "/wims/list/",
+                "dataSrc": function (json) {
+                    return json['datacenters'];
+                },
+                statusCode: {
+                    401: function () {
+                        console.log("no auth");
+                        moveToLogin(window.location.pathname);
+                    }
+                },
+                "error": function (hxr, error, thrown) {
+                    console.log(hxr)
+                    console.log(thrown)
+                    console.log(error);
+                }
+
+            },
+            "columns": [
+                {
+                    "render": function (data, type, row) {
+                        return row["name"];
+                    },
+                    "targets": 0
+                },
+                {
+                    "render": function (data, type, row) {
+                        return row['_id'];
+                    },
+                    "targets": 1
+                },
+                {
+                    "render": function (data, type, row) {
+                        return row["wim_type"];
+                    },
+                    "targets": 2
+                },
+                {
+                    "render": function (data, type, row) {
+                        return row["_admin"]['operationalState'];
+                    },
+                    "targets": 3
+                },
+                {
+                    "render": function (data, type, row) {
+                        return row['description'] || '';
+                    },
+                    "targets": 4
+                },
+                {
+                    "render": function (data, type, row) {
+                        return '<div class="btn-group"><button type="button" class="btn btn-default" ' +
+                            'onclick="javascript:showWIM( \''+row['_id'] + '\', \''+row['name'] +'\')" data-toggle="tooltip" data-placement="top" data-container="body" title="Show Info">' +
+                        '<i class="fa fa-info"></i>' +
+                        '</button> ' +
+                        '<button type="button" class="btn btn-default"' +
+                        'onclick="javascript:deleteWim(\''+row['_id']+'\', \''+ row["name"] +'\')" data-toggle="tooltip" data-placement="top" data-container="body" title="Delete">' +
+                        '<i class="far fa-trash-alt" ></i></button></div>';
+                    },
+                    "targets": 5,
+                    "orderable": false
+                }
+            ]
+        });
+
+        setInterval(function () {
+                table.ajax.reload();
+            }, 10000);
+    });
+
+        function openModalCreateWIM(){
+            $('#modal_new_wim').modal('show');
+        }
+        function deleteWim(wim_id, wim_name) {
+            var url = "/wims/"+wim_id+"/delete";
+            bootbox.confirm("Are you sure want to delete " + wim_name + "?", function (result) {
+                if (result) {
+                    var dialog = bootbox.dialog({
+                        message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+                        closeButton: true
+                    });
+                    $.ajax({
+                        url: url,
+                        type: 'GET',
+                        dataType: "json",
+                        contentType: "application/json;charset=utf-8",
+                        success: function (result) {
+                            if (result['error'] == true) {
+                                dialog.modal('hide');
+                                bootbox.alert("An error occurred.");
+                            }
+                            else {
+                                dialog.modal('hide');
+                                location.reload();
+                            }
+                        },
+                        error: function (error) {
+                            dialog.modal('hide');
+                            bootbox.alert("An error occurred.");
+                        }
+                    });
+                }
+            })
+        }
+
+        function showWIM(wim_uuid) {
+            var dialog = bootbox.dialog({
+                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+                closeButton: true
+            });
+
+            $.ajax({
+                url: '/wims/' + wim_uuid ,
+                type: 'GET',
+                dataType: "json",
+                contentType: "application/json;charset=utf-8",
+                success: function (result) {
+                    //$('#modal_show_vim_body').empty();
+                    var wim = result.wim;
+                    
+                    if (wim) {
+                        $('#modal_show_wim_body').find('span').text('-');
+                        for (var k in wim) {
+                            $('#' + k).text(wim[k])
+                        }
+                        if (wim['_admin']) {
+                            for (var i in wim['_admin']) {
+                                if (i === 'modified' || i === 'created') {
+                                    //$('#' + i).text(new Date(wim['_admin'][i]* 1000).toUTCString());
+                                    $('#' + i).text(moment(wim['_admin'][i] * 1000).format('DD/MM/YY hh:mm:ss'));
+                                }
+                                else if (i === 'deployed') {
+                                    $('#' + i).text(JSON.stringify(wim['_admin'][i]))
+                                }
+                                else
+                                    $('#' + i).text(wim['_admin'][i])
+                            }
+                        }
+                        dialog.modal('hide');
+                        $('#modal_show_wim').modal('show');
+                    }
+                    else {
+                        dialog.modal('hide');
+                        bootbox.alert("An error occurred while retrieving the WIM info.");
+                    }
+
+                },
+                error: function (result) {
+                    dialog.modal('hide');
+                    bootbox.alert("An error occurred while retrieving the WIM info.");
+                }
+            });
+
+        }
+    </script>
+
+{% endblock %}
diff --git a/wimhandler/urls.py b/wimhandler/urls.py
new file mode 100644
index 0000000..94b9645
--- /dev/null
+++ b/wimhandler/urls.py
@@ -0,0 +1,24 @@
+#   Copyright 2018 EveryUP Srl
+#
+#   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  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.
+
+from django.conf.urls import url
+from wimhandler import views
+
+urlpatterns = [
+    url(r'^list/', views.list, name='list'),
+    url(r'^create/', views.create, name='create'),
+    url(r'^(?P<wim_id>[0-9a-z-]+)/delete$', views.delete, name='delete'),
+    url(r'^(?P<wim_id>[0-9a-z-]+)', views.show, name='show'),
+
+]
\ No newline at end of file
diff --git a/wimhandler/views.py b/wimhandler/views.py
new file mode 100644
index 0000000..c885b60
--- /dev/null
+++ b/wimhandler/views.py
@@ -0,0 +1,109 @@
+#   Copyright 2018 EveryUP Srl
+#
+#   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  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.
+
+from django.shortcuts import render, redirect
+from sf_t3d.decorators import login_required
+from django.http import HttpResponse
+import json
+from lib.osm.osmclient.clientv2 import Client
+import authosm.utils as osmutils
+import yaml
+import logging
+
+logging.basicConfig(level=logging.DEBUG)
+log = logging.getLogger('wimhandler.py')
+
+
+@login_required
+def list(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    result = {'type': 'ns', 'project_id': project_id}
+    raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
+    if 'application/json' not in raw_content_types:
+        return __response_handler(request, result, 'wim_list.html')
+    client = Client()
+    result_client = client.wim_list(user.get_token())
+    result["datacenters"] = result_client['data'] if result_client and result_client['error'] is False else []
+    return __response_handler(request, result, 'wim_list.html')
+
+@login_required
+def create(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    result = {'project_id': project_id}
+    if request.method == 'GET':
+        return __response_handler(request, result, 'wim_create.html')
+    else:
+        new_wim_dict = request.POST.dict()
+        client = Client()
+        keys = ["schema_version",
+                "schema_type",
+                "name",
+                "description",
+                "wim_url",
+                "wim_type",
+                "user",
+                "password",
+                "wim",
+                "description"]
+        wim_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_wim_dict.items()))
+        wim_data['config'] = {}
+        for k, v in new_wim_dict.items():
+            if str(k).startswith('config_') and len(v) > 0:
+                config_key = k[7:]
+                wim_data['config'][config_key] = v
+        if 'additional_conf' in new_wim_dict:
+            try:
+                additional_conf_dict = yaml.safe_load(new_wim_dict['additional_conf'])
+                for k,v in additional_conf_dict.items():
+                    wim_data['config'][k] = v
+            except Exception as e:
+                # TODO return error on json.loads exception
+                print e
+        result = client.wim_create(user.get_token(), wim_data)
+        return __response_handler(request, result, 'wims:list', to_redirect=True, )
+
+@login_required
+def delete(request, wim_id=None):
+    user = osmutils.get_user(request)
+    try:
+        client = Client()
+        del_res = client.wim_delete(user.get_token(), wim_id)
+    except Exception as e:
+        log.exception(e)
+    return __response_handler(request, del_res, 'wims:list', to_redirect=True, )
+
+@login_required
+def show(request, wim_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    client = Client()
+    result = client.wim_get(user.get_token(), wim_id)
+    if isinstance(result, dict) and 'error' in result and result['error']:
+        return render(request, 'error.html')
+
+    return __response_handler(request, {
+        "wim": result['data'],
+        "project_id": project_id
+    }, 'wim_show.html')
+
+def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
+    raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
+    if 'application/json' in raw_content_types or url is None:
+        return HttpResponse(json.dumps(data_res), content_type="application/json", *args, **kwargs)
+    elif to_redirect:
+        return redirect(url, *args, **kwargs)
+    else:
+        return render(request, url, data_res)
\ No newline at end of file