<!doctype html>
<head>
    <link href="data:image/x-icon;base64,AAABAAEAEBAAAAAAAABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////AAAAAJ4YGAClFxcApRcXAKUWFgCkFRUApBQUAKQTEwCjEhIAoxESAKMREgCjAAAAnv///wAAAAAAAAAAAAAAAJ6zHQn/sx0J/7MdCf+zHQn/sx0J/7MdCf+zHQn/sx0J/7MdCf+zHQn/sx0J/7MdCf8BAQCfAAAAAAAAAAAREQCjsx0Ju7MdCbuzHQn/sx0J/7MdCf+zHQn/sx0J/7MdCf+zHQn/sx0J/7MdCf+zHQm7CwsAoQAAAAAAAAAAAAAARLMdCbuzHQm7sx0J/7MdCf+zHQn/sx0J/7MdCf+zHQn/sx0J/7MdCf+zHQm7sx0J/wAAAD4AAAAAAAAAAP///wAkJACosx0JlbMdCbuzHQn/sx0J/7MdCf+zHQn/sx0J/7MdCf+zHQn/sx0J/wAAAJ7///8AAAAAAAAAAAD///8AnZ2dCbMdCZWzHQm7sx0Ju7MdCf+zHQn/sx0J/7MdCf+zHQn/sx0JuzAvAqz///8A////AAAAAAAAAAAA////AP///wAAAABWsx0JlbMdCbuzHQm7sx0J/7MdCf+zHQn/sx0Ju7MdCf8AAAA/////AP///wAAAAAAAAAAAP///wD///8A////ACAgAKf8/6Bv/P+TXvz/AC/8/wAs/P8AKvz/llACAgCf////AP///wD///8AAAAAAAAAAAD///8A////AP///wCoqKgJaWsAiP3/oWj8/wAw/P8ALfz/i008PQCn/v7+AP///wD///8A////AAAAAAAAAAAA////AP///wD///8A////AAAAAFbW2ABB+/9rTfz/AC6PkQBRAAAAQP///wD///8A////AP///wAAAAAAAAAAAP///wD///8A////AP///wDt7e0EgYMAZ/v/ak9OTwCWP0AAr////wD///8A////AP///wD///8AAAAAAAAAAAD///8A////AP///wD///8AjY2NBoKEAGf9/2BP/P8AL2xtAGn///8A////AP///wD///8A////AAAAAAAAAAAA////AP///wD///8A////AI2NjQqEhQBn/P9JTfz/ADBpaQBz////AP///wD///8A////AP///wAAAAAAAAAAAP///wD///8A////AP///wCNjY0LhogAZ/z/REv8/wAxYGEAfv///wD///8A////AP///wD///8AAAAAAAAAAAD///8A////AP///wD///8AAAAAPMHEAE37/wA1/P8AMXd4AGLj4+MB////AP///wD///8A////AAAAAAAAAAAA////AP///wD///8A////AB8fAKcdHgCmHBwAphsbAKYaGgClBAUAoP///wD///8A////AP///wAAAAAAwAMAAIABAACAAQAAwAMAAMADAADgBwAA8A8AAPfvAAD73wAA//8AAP8/AAD//wAA//8AAP//AAD//wAA+B8AAA==" rel="icon" type="image/x-icon" />
    <title>Charts &amp; Histograms  - Yahi</title>
    
<style>

* { margin:0; padding:0}
.horizontal { 
display:block;
margin:auto;
background:#46B;
padding:.7em 0;
}
a:visited, a { color:#46A}
.horizontal li { display:inline; list-style-type: none; color:white; }
.horizontal li a { margin-left:3px;margin-right:2px; padding: .7em; color:white;}
.horizontal li a:hover { border:1px solid grey;margin:-1px;color:#46A; background: white;display: inline;  padding-right: 1em; }
body         {
    font-family: 'Georgia', serif; font-size: 100% ; color: #000; 
    }
#plotbox     { 
    width:95%;

    border:1px solid lightgrey;
    margin:auto;
    text-align:center;
    }
#plot   { 
    
    max-width:1900px;
    background:#f0f0fF;
    min-height:300px;
   margin-bottom:1em;

    }
.centered { 
    margin: auto ; 
    padding:0;
    text-align:center; 
    }
h1, h2, h3   { font-family: 'Georgia', serif; font-weight: normal; }
.header      { height: 165px; }
               font-size: 50px; padding-top: 50px; height: 120px; }
h2           { font-size: 24px; margin: 25px 0 5px 0; }
.json { }
pre          { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono',
               'Bitstream Vera Sans Mono', monospace!important; font-size: 15px;
               background: #eee; }
.footer      { position:fixed; bottom:0px; text-align: center;left:0;right:0  }
</style>

    <script src="https://d3js.org/d3.v6.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
        <script type='text/javascript' src='https://www.google.com/jsapi'></script>




</head>
<body>
<div class=centered style="width:100%" >
<span style="line-height:1.4em">Built with 
<a href=http://github.com/jul/yahi>yahi</a> 
&amp; <a href=http://archery.readthedocs.org>archery</a>
// &copy; Copyright (2012) <a href="http://github.com/jul">jul</a> &amp;
  <a href="http://github.com/19emtuck">19emtuck</a> &amp; 
        <a href=https://github.com/bmispelon/ >bmispelon</a></span>
<ul class=horizontal >
<li id=top ><em>Type of presentation:</em></li>
<li><a class=router href=?route=geo >geo chart</a></li>
<li><a class=router href=?route=top >histograms</a></li>
<li><a class=router href=?route=chrono >time series</a></li>
<li><a class=router href=?route=raw >raw data</a></li>


</ul>
</div>



    <div id="content">
  <div id="chart_div" class="centered content geo" style="left:7%;right:7%;position:absolute;width: 80%;top:5em;bottom:2em;border:1px solid lightgrey"></div>

<div id="plotbox" class="content centered top chrono" >
    <h2 class="content top">Top requests <span class=top id=ctitle > by status</span></h2>
    <h2 class="content chrono" >Chronologicial <span class=chrono id=ctitle > by status</span></h2>
    <div id=plot class=centered ></div>
</div>
<pre class="content raw" >
{{DATA}}
</pre>

</div>
    <div id='#footer' class="footer">
        

<div style="height:1px"></div>
<ul class="content top horizontal" id="menu_down" >
    <li><em>Charts Availables</em> </li>
</ul>
<ul id=menu_down class="content horizontal chrono">
    <li><em>Chronological series available  :</em> </li>
</ul>


    </div>
<script>
// set the dimensions and margins of the graph
function _keys(arr) {
    var arrr=[];
    $.each( arr, function(k,v) { arrr.push( k )});
    return arrr;

}
function _values(arr) {
    var arrr=[];
    $.each( arr, function(k,v) { arrr.push( v )});
    return arrr;

}

$(document).ready(function() {
    data = JSON.parse($("pre").text())
    const max_ticks=40;
    if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' ) {
         $(".footer").css("position", "static");
    };
    //create sub routes py parsing json
    $.each(_keys(data), (i,e) => {
        if ( e.substring(0,3) == "by_" )
            $('#menu_down.top').append("<li><a id="+e+" class=selector href=#" + e + "?route=top >" + e + "</a></li>")
        if ( e.substring(0,5) == "date_" ||  e.substring(0,5) == "hour_" )
            $('#menu_down.chrono').append("<li><a id="+e+" class=selector href=#" + e + "?route=chrono >" + e + "</a></li>")
    })
    $(".router").each( (i,e) => {
        var query = new URLSearchParams( e.attributes.href.value )
        $(e).addClass(query.get("route"))
    })
        $(".selector").each( (i,e) => {
        $(e).addClass($(e).attr("href").substr(1).replace(/\?.*/,""))
    })
    $(".selector", ".top").click(function(e) {
        e.preventDefault()
        history.pushState({} ,"", $(this).attr("href").replace(/\?.*/,""));
        update_for( ($(this).attr("href")).substring(1).replace(/\?.*/,""),max_ticks );
        console.log($(this).attr("href"))
        $("#ctitle", ".top").text( $(this).text());
        return false;
    });
    $(".selector", ".chrono").click(function(e) {
        e.preventDefault()
        history.pushState({}, "",$(this).attr("href").replace(/\?.*/,"")  );
        update_for( ($(this).attr("href")).substring(1).replace(/\?.*/,"" ));
        console.log("href:" + $(this).attr("href"))
        $("#ctitle.chrono" ).text( $(this).text());

       return false;
    });
    if (data["by_country"] == undefined) {
        console.log("geo is hidden since there is no by_country data")
        $(".router.geo").hide()
    }
    anchor = document.URL.match(/#[^\?]+/)
    console.log("nchor"+anchor)
    $(".router").click( (e) => {
        e.preventDefault()
        var href=$(e.target)[0].attributes.href
        var query = new URLSearchParams( $(e.target)[0].attributes.href.value )


        url = href.value

        var route = query.get("route")
            anchor = document.URL.match(/#[^\?]+/)

        if (anchor)
            url += anchor
        history.pushState({}, null,  url)
        var query = new URLSearchParams( url)
        console.log("route:" + route);
        ({
            "chrono": () => { 
                $(".content").hide(); $("." + route).show();
                $(".selector",".chrono")[0].click()
            },
            "top": () => { 
                $(".content").hide(); $("." + route).show() 
                $(".selector",".top")[0].click()
            },
            "raw": () => { $(".content").hide(); $("." + route).show() 
            },
            "geo": () => { 
                google.load('visualization', '1', {'packages' : ["geochart"]});
                $(".content").hide(); $("." + route).show()
                function fucking_google_callbak() {
                var items = [["Country","popularity"]];
                for( key in data["by_country"]){
                    val = data["by_country"][key] * 1 ;
                    items.push( [key, val ] )
                };
                data2 = google.visualization.arrayToDataTable(items);
                    var chart = new google.visualization.GeoChart(
                        document.getElementById('chart_div'));
                    chart.draw(data2, {});
                };
                google.setOnLoadCallback( fucking_google_callbak);
            }
        })[route]()
        return false
    })
    anchor = document.URL.match(/#[^\?]+/)

    var query = new URLSearchParams(window.location.search )
    route = query.get("route")
    if (route == undefined ) {
        console.log("default route")
        $(".router.top").click()
        $("top > .selector")[0].click()

    } else {
        $(".router." + route).click()
    }
    console.log("anchor is " + anchor)
    if (anchor != undefined){
        console.log( ".selector." +  anchor[0].substr(1))

        $(".selector." +  anchor[0].substr(1)).click()
    }
    console.log("ready")

    function update_for(category, top){

        // set the dimensions and margins of the graph
        const margin = {top: 30, right: 30, bottom: 170, left: 160},
            width = 1000 - margin.left - margin.right,
            height = 400 - margin.top - margin.bottom;

        // append the svg object to the body of the page
        $("#plot > svg").remove()
        const svg = d3.select("#plot")
          .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
          .append("g")
            .attr("transform", `translate(${margin.left},${margin.top})`);


        serie = data[category]
        serie = _keys(serie).map((e,i) => [ e, serie[e] ])
        k = serie.map(d => d[0])

        if (top) {
            console.log("sorting")
            serie=serie.sort(function(a, b) {
                a =  a[1];
                b =  b[1];
                return a < b ? -1 : (a > b ? 1 : 0);
            }).reverse().slice(0,max_ticks);
            console.log(serie)
        } else {

            console.log("sorting")
            serie=serie.sort(function(a, b) {
                a =  a[0];
                b = b[0];
                return a < b ? -1 : (a > b ? 1 : 0);
            }).slice(0,max_ticks);
            console.log(serie)


        }
        // X axis
        const x = d3.scaleBand()
          .range([ 0, width ])
          .domain(serie.map( (e) => ""+ e[0]))
          .padding(0.2);
        svg.append("g")
          .attr("transform", `translate(0, ${height})`)
          .call(d3.axisBottom(x))
          .selectAll("text")
            .attr("transform", "translate(-10,0)rotate(-45)")
            .style("text-anchor", "end");

        // Add Y axis
        maxou = Math.max.apply(null, _values(serie).map((e) => e[1]))
        const y = d3.scaleLinear()
          .domain([0, maxou])
          .range([ height, 0]);
        svg.append("g")
          .call(d3.axisLeft(y));

        // Bars
        console.log("serie before making bars")
        console.log(serie)
        svg.selectAll("mybar")
          .data(serie)
          .join("rect")
            .attr("x", d => x( d[0] ))
            .attr("y", d => y(d[1]))
            .attr("width", x.bandwidth())
            .attr("height", d => 1 * ( height - y(d[1])))
            .attr("fill", "#46A")
            .attr("stroke", "#eef")
        if (!top) {
            console.log("too much ticks")
            console.log(k.length)
            if (k.length > (max_ticks)) {
                every= Math.floor(k.length/(max_ticks))
                var ticks = d3.selectAll(".tick text");
                ticks.each(function(_,i){
                    if(i%every !== 0) d3.select(this).remove();
                });

            }
        }
    }
});

</script>
</body>
