{% extends 'base.html' %}
{% load compress %}
{% load i18n %}
{% load i18n sizeformat %}

{% block title %}{% trans "Usage Costs" %}{% endblock %}

{% block css %}
    {% include "_stylesheets.html" %}

    <link href="{{ STATIC_URL }}catalystdashboard/nv.d3.min.css" rel="stylesheet" type="text/css">
    <link href='{{ STATIC_URL }}catalystdashboard/scss/style.css' type='text/css' rel='stylesheet'>
{% endblock %}

{% block page_header %}
  {% include "horizon/common/_page_header.html" with title=_("Usage Costs") %}
{% endblock page_header %}

{% block main %}

<p>Disclaimer: This is an estimate for your usage cross <b>ALL regions</b>, not your final invoice. It includes the free router and network discount. All costs are in New Zealand dollars and are exclusive of GST.</p>

<div class="row-fluid">
    <div id="credits_div" class="list-group">
       <h4 class="quota-heading dot_line">{% trans "Credits" %}</h4>
       <ul id="credits_list" class="fa-ul" style="margin-left: 1.7em">
       </ul>
    </div>
    <div>
        <h4 class="quota-heading dot_line">{% trans "Usage Cost History" %}
        </h4>
        <div id="line_chart">
            <svg class="line"></svg>
        </div>
    </div>

    <div>
        <h4 id="monthly_title" class="quota-heading dot_line">{% trans "Monthly Cost Break Down" %}</h4>
        <div class="col-md-4" style="padding:0px;">
            <div id="pie_chart">
               <select id="month_select" class="form-control" style="width:95%;"></select>
               <svg class="pie"></svg>
            </div>
        </div>
        <div class="col-md-8" style="padding:0px;">
            <table id="month_details" class="table table-striped">
                <thead>
                    <tr>
                        <th>Product Name</th>
                        <th>Resource Name/ID</th>
                        <th>Quantity</th>
                        <th>Unit</th>
                        <th>Rate</th>
                        <th>Cost</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>Product Name</th>
                        <th>Resource Name/ID</th>
                        <th>Quantity</th>
                        <th>Unit</th>
                        <th>Rate</th>
                        <th>Cost</th>
                    </tr>
                </tfoot>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Current d3 version is 3.4.1 -->
<script type="text/javascript" src="{{ STATIC_URL }}catalystdashboard/d3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="{{ STATIC_URL }}catalystdashboard/nv.d3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="{{ STATIC_URL }}catalystdashboard/jquery.simplePagination.js" charset="utf-8"></script>
<script type="text/javascript">
    var LINE_CHART_DATA = {{line_chart_data | safe}};
    var PIE_CHART_DATA = {{pie_chart_data | safe}};
    var MONTH_DETAILS = {{month_details | safe}};
    var MONTHS = {{x_axis_line_chart | safe}};
    var CREDITS = {{credits | safe}};

    function draw_pie(where, source){
        var h = 500;
        var r = h/2;
        var arc = d3.svg.arc().outerRadius(r) /2 ;
        nv.addGraph(function() {
            var chart = nv.models.pieChart()
                .x(function(d) { return d.key })
                .y(function(d) { return d.value })
                .margin({left: 0, right: 50})
                .showLabels(true)
                .labelType("percent")
                .labelThreshold(.05)
                .donut(true).donutRatio(0.35);
            d3.select("#pie_chart svg")
                .datum(source)
                .transition().duration(1200)
                .call(chart);
            return chart;
        });
    }

    function draw_line(where, source){
        nv.addGraph(function() {
            d3.select(source).remove();
            var chart = nv.models.lineChart()
                .margin({left: 75, right: 50})
                .size(100);

            chart.tooltipContent(function(key, x, y, graph) {
                pay_status = "";
                if (key == "Cost"){
                    status = LINE_CHART_DATA[0].values[MONTHS.indexOf(x)].p;
                    pay_status = "<br/>which is a quotation";
                    switch(status) {
                        case "paid":
                            pay_status = "<br/>which has been paid";
                            break;
                        case "open":
                            pay_status = '<br/>which has <strong style="color: #E6550D;">NOT</strong> been paid';
                            break;
                        default:
                            text = "<br/>which is a quotation";
                    }
                }
                return '<h3>' + key + '</h3>' + '<span style=\'padding:8px\'>$' + y + ' at ' + x + pay_status + '</span>'
            });

            chart.legend
                .radioButtonMode(true);

            chart.xAxis.axisLabel("Cost per Month")
                .tickValues([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
                .tickFormat(function(m){return MONTHS[m]});

            chart.yAxis
                .axisLabel("Cost (NZD) excl. GST")
                .tickFormat(d3.format(',.2f'));
            d3.select(where).select('.nv-interactive').selectAll("circle").remove();
            d3.select(where)
                .datum(source)
                .transition()
                .duration(500)
                .call(chart)
                .each("end", function(){
                    var svg = d3.select(this);
                    var data = LINE_CHART_DATA;
                    var unpaid = svg.select('.nv-interactive').selectAll("circle")
                        .data(data[0].values.filter(function (d) {
                        return d.p == 'open';
                    }))
                        .enter().append("circle")
                        .attr("class", "unpaid")
                        .style("fill", "#E6550D")
                        .attr("r", 6)
                        .attr("cx", function(d) {
                        return chart.xAxis.scale()(d.x);
                    })
                        .attr("cy", function(d) {
                        return chart.yAxis.scale()(d.y);
                    });
                    //    .on("click", function(d) {
                    //        showMonthlyCost(d["x"]);
                    //});

                    current_month = LINE_CHART_DATA[0].values[11];
                    var current = svg.select('.nv-interactive')
                        .append("circle")
                        .attr("class", "mycircle")
                        .style("fill", "#31A354")
                        .attr("r", 6)
                        .attr("cx", function(d) {return chart.xAxis.scale()(current_month.x);})
                        .attr("cy", function(d) {return chart.yAxis.scale()(current_month.y);});
                });

            nv.utils.windowResize(chart.update);

            return chart;
        });
    }


    function showMonthlyCost(monthIndex){
        // Build the details table
        var link_mapping = {"c1": "/project/instances/",
                            "b1": "/project/volumes/"}
        $('#month_details tbody').empty();
        if (MONTH_DETAILS.length == 0) {return}
        month_detail = MONTH_DETAILS[monthIndex]
        for(i = 0; i < month_detail.length; i++) {
            var resource_id = ""
            var resource_url = "#";
            if (month_detail[i]['resource_id'] != null && month_detail[i]['resource_id'] != "") {
                resource_id = "(" + month_detail[i]['resource_id']+")"
                var resource_type = month_detail[i]["product"].split(".")[1];
                var product_name = month_detail[i]["product"].split(".")[2];
                if (resource_type in link_mapping){
                    resource_url = link_mapping[resource_type] + month_detail[i]['resource_id'];
                }
                if (resource_type == 'n1'){
                    if (product_name == 'network'){
                        resource_url = '/project/networks/'+ month_detail[i]['resource_id'] +'/detail';
                    }
                    if (product_name == 'router'){
                        resource_url = '/project/routers/'+ month_detail[i]['resource_id'];
                    }
                    if (product_name == 'vpn'){
                        resource_url = '/project/vpn/vpnservice/'+ month_detail[i]['resource_id'];
                    }
                }
            }

            resource = resource_id == ""? month_detail[i]['resource_name']+resource_id : "<a href="+ resource_url +">" + month_detail[i]['resource_name'] + resource_id + "</a>"
            $('#month_details tbody').append('<tr><td>' + month_detail[i]['product'] + '</td><td>' + resource +'</td><td>'+month_detail[i]['quantity']+'</td><td>'+month_detail[i]['unit']+'</td><td>'+month_detail[i]['rate']+'</td><td>$'+month_detail[i]['cost']+'</td></tr>');
        }

        $("#month_details").simplePagination({
            perPage: 10,
        });

        // Refresh the pie chart
        draw_pie("#pie_chart .pie", function(){
            return PIE_CHART_DATA[monthIndex];
        });
    }

    $(document).ready(function(){
        draw_line("#line_chart .line", function(){
            return LINE_CHART_DATA;
        });

        $(window).resize(function(){
            draw_line("#line_chart .line", function(){
                return LINE_CHART_DATA;
            });
        });

        for(i = MONTHS.length -1 ; i >= 0; i--) {
            amount = LINE_CHART_DATA[0].values[i]["y"]
            $("#month_select").append('<option value="'+ i.toString() +'">'+MONTHS[i] + ': $' + amount +'</option>');
        }
        $("#month_select").change(function (e) {
            var optionSelected = $("option:selected", this);
            var valueSelected = this.value;
            showMonthlyCost(this.value);
        });

        showMonthlyCost(11);

        if (CREDITS["credits"].length == 0) {
            $("#credits_div").hide();
        } else {
             $("#credits_div").show();
            for(i=0;i<CREDITS["credits"].length;i++){
                $("#credits_list").append('<li><i class="fa-li fa fa-credit-card"></i> Balance of ' + CREDITS["credits"][i].type + ' is $' + CREDITS["credits"][i].balance + '. This will expire on ' + CREDITS["credits"][i].expiry_date + '</li>');
            }
        }
    });

</script>

{% endblock %}
