{% 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 within the current region, 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 class="col-md-4">
        <h3 class="quota-heading dot_line">{% trans "Month to date" %}</h3>
        <div id="pie_chart">
            <svg class="pie"></svg>
        </div>

        {{table.render}}
    </div>

    <div class="col-md-8">
      <h3 class="quota-heading dot_line">{% trans "Usage cost history" %}</h3>
      <!-- Remove the date range for now
      <form action="?" method="get" id="date_form" class="form-horizontal">
        <h3>{% trans "Select a period of time to query its cost" %}: </h3>
        <div class="datepicker">
            {% blocktrans with start=form.start %}
            <label>From:</label>{{ start }}{% endblocktrans %}

            {% blocktrans with end=form.end %}
            <label>To:</label>{{ end }}{% endblocktrans %}
            <button class="btn btn-primary" type="submit">{% trans "Submit" %}</button>
            <small>{% trans "The date should be in YYYY-mm-dd format." %}</small>
        </div>
      </form>
      -->

      <div id="line_chart">
        <svg class="line"></svg>
      </div>
      <table id="service_details" class="table table-striped datatable  tablesorter tablesorter-default">
         <thead>
           <tr class="table_caption">
             <th data-column="0" class="table_header" colspan="6">
               <h3 class="table_title">Usage Details</h3>
             </th>
           </tr>
           <tr class="tablesorter-headerRow">
            <th tabindex="0" data-column="0" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Resource ID</div></th>
            <th tabindex="0" data-column="1" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Resource Name</div></th>
            <th tabindex="0" data-column="2" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Volume</div></th>
            <th tabindex="0" data-column="3" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Unit</div></th>
            <th tabindex="0" data-column="4" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Rate</div></th>
            <th tabindex="0" data-column="5" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Cost</div></th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </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">
    var CHART_DATA = {{chart_data | safe}};
    var AMOUNT_COST = {{amount_cost | safe}};
    var COST_DETAILS = {{cost_details | safe}};

    function draw_pie(where, source){
        nv.addGraph(function() {
            var chart = nv.models.pieChart()
                .x(function(d) { return d.key })
                .y(function(d) { return d.value })
                .showLabels(true)
                .labelType("percent")
                .labelThreshold(.05)
                .donut(true)
                .donutRatio(0.35);

            chart.tooltipContent(function(k, v, graph) {
                return '<h3>' + k + '</h3>' + '<span style=\'padding:8px\'>$' + v + '</span>'
            });

            d3.select(where)
                .datum(source)
                .transition().duration(1200)
                .call(chart);

            nv.utils.windowResize(chart.update);

            return chart;
        });
    }

    function draw_line(where, source){
        nv.addGraph(function() {
            var months = {{x_axis_line_chart | safe}};
            var chart = nv.models.lineChart()
                .margin({left: 75})
                .size(70);

            chart.tooltipContent(function(key, x, y, graph) {
                return '<h3>' + key + '</h3>' + '<span style=\'padding:8px\'>$' + y + ' at ' + x + '</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)
                .datum(source)
                .call(chart);

            nv.utils.windowResize(chart.update);

            return chart;
        });
    }

    $(document).ready(function(){
        draw_pie("#pie_chart .pie", function(){
            return CHART_DATA['pie'];
        })

        draw_line("#line_chart .line", function(){
            return CHART_DATA['line'];
        })

        $('#id_start').attr('disabled', true);
        $('#billing tbody tr').each(function(){
            $(this).find("td").eq(2).html('$' + $(this).find("td").eq(2).html());
        });
        $('#billing tfoot td').attr('colspan', 2);
        $('#billing tfoot>tr').append('<td><span class="total">$'+AMOUNT_COST+'</span></td>');

        var link_mapping = {"Compute": "/instances/",
                            "Image": "/images/",
                            "Network": "/networks/",
                            "Router": "/routers/",
                            "Block Storage": "/volumes/",
                            "VPN": "/vpn/vpnservice/"}
        $("#billing tbody>tr a")
          .click(function() {
            var resource_type = $(this).html();
            res_cost_details = COST_DETAILS[resource_type]
             $('#service_details .table_title').html(resource_type + ' - Usage Details')
            $('#service_details').show();
            $('#service_details tbody').html('');
            if (res_cost_details.length>0){
                for (i = 0; i < res_cost_details.length; i++) {
                    var row_class = i%2==0? 'odd':'even';
                    var link = "#";
                    if (resource_type in link_mapping){
                        link = "/project" + link_mapping[resource_type] + res_cost_details[i]['resource_id'];
                    }
                    if (resource_type == 'Network'){
                        link += '/detail';
                    }

                    $('#service_details tbody').append('<tr class='+row_class+'><td><a href="' + link +'">' + res_cost_details[i]['resource_id'] + '</a></td><td>'+res_cost_details[i]['resource']+'</td><td>'+res_cost_details[i]['volume']+'</td><td>'+res_cost_details[i]['unit']+'</td><td>'+res_cost_details[i]['rate']+'</td><td>'+res_cost_details[i]['cost']+'</td></tr>');
                }
            }
          })
        $('#service_details').hide();
    });

</script>

{% endblock %}
