//===========================================================================//
// Visoalisation formation D3.js                      Par Jérémy FOUQUAT     //
//===========================================================================//


//=============================================//
//            1. Dataset management            //
//=============================================//
let dataset = null;
d3.csv("shot_logs.csv", function(error, data) {

    //=========================================//
    // 1.1. Select and rename attributes       //
    //=========================================//
    dataset_field_goal = data.map( function(d){
        return {
            matchup: d.MATCHUP,
            location_game: d.LOCATION,
            shot_number: d.SHOT_NUMBER,
            dribbles: d.DRIBBLES,
            touch_time: d.TOUCH_TIME,
            shot_dist: d.SHOT_DIST,
            pts_type: d.PTS_TYPE,
            shot_result: d.SHOT_RESULT,
            fgm: d.FGM,
            pts: d.PTS,
            player_name: d.player_name,
            player_id: d.player_id
        }
    });

    //=========================================//
    // 1.2. Call visualisation function        //
    //=========================================//

    visualisation_01(dataset_field_goal);

});


//=============================================//
//         2. Visualisation management         //
//=============================================//
function visualisation_01(dataset){

    //=========================================//
    // 2.1. Variables management               //
    //=========================================//
    let dataset_reworked = [],
        dataset_reworked_home = [],
        dataset_reworked_away = [],

        x_domain_min = 0,
        x_domain_home_max = 0,
        x_domain_away_max = 0,
        y_domain_min = 0,
        y_domain_home_max = 0,
        y_domain_away_max = 0,

        x_scale = null,
        y_scale = null,
        y_scale_home = null,
        y_scale_away = null,

        svg_width = 1024,
        svg_height = 728,

        margin_top = 20,
        margin_bottom = 20,
        margin_left = 20,
        margin_right = 20,

        padding_top = 20,
        padding_bottom = 40,
        padding_left = 40,
        padding_right = 40,

        width = svg_width - margin_left - margin_right - padding_left - padding_right,
        height = svg_height - margin_top - margin_bottom - padding_top - padding_bottom,

        svg_viz = null,
        x_grid_chart = null,
        y_grid_chart = null,
        x_axis_chart = null,
        y_axis_left_chart = null,
        y_axis_right_chart = null,
        chart = null,
        tooltip_chart = null;


    //=========================================//
    // 2.2. Dataset modifications              //
    //=========================================//
    dataset.forEach(function(d,i) {

        // Première insertion
        if (dataset_reworked.find( function(elem) { return elem.nom == d.player_name; } ) == undefined) {
            dataset_reworked.push({nom: d.player_name, fgm: Number(d.fgm), fga: 1});

            if (d.location_game[0] == 'H' ) {
                dataset_reworked_home.push({nom: d.player_name, fgm: Number(d.fgm), fga: 1});
                dataset_reworked_away.push({nom: d.player_name, fgm: 0, fga: 0});
            }
            if (d.location_game[0] == 'A' ) {
                dataset_reworked_away.push({nom: d.player_name, fgm: Number(d.fgm), fga: 1});
                dataset_reworked_home.push({nom: d.player_name, fgm: 0, fga: 0});
            }
        }

        // Ajout de données
        else {
            dataset_reworked[ dataset_reworked.findIndex( function(elem) {
                              return elem.nom == d.player_name;
                            })
                          ].fgm += Number(d.fgm) ;
            dataset_reworked[ dataset_reworked.findIndex( function(elem) {
                              return elem.nom == d.player_name;
                            })
                          ].fga++ ;
            if (d.location_game[0] == 'H' ) {
                dataset_reworked_home[ dataset_reworked_home.findIndex( function(elem) {
                                  return elem.nom == d.player_name;
                                })
                              ].fgm += Number(d.fgm) ;
                dataset_reworked_home[ dataset_reworked_home.findIndex( function(elem) {
                                  return elem.nom == d.player_name;
                                })
                              ].fga++ ;
            }
            if (d.location_game[0] == 'A' ) {
                dataset_reworked_away[ dataset_reworked_away.findIndex( function(elem) {
                                  return elem.nom == d.player_name;
                                })
                              ].fgm += Number(d.fgm) ;
                dataset_reworked_away[ dataset_reworked_away.findIndex( function(elem) {
                                  return elem.nom == d.player_name;
                                })
                              ].fga++ ;
            }
        }
    });


    //=========================================//
    // 2.3. Domains and scales management      //
    //=========================================//
    x_domain_home_max = d3.max(dataset_reworked_home, function(d) { return d.fga; });
    x_domain_away_max = d3.max(dataset_reworked_away, function(d) { return d.fga; });
    y_domain_home_max = d3.max(dataset_reworked_home, function(d) { return d.fgm; });
    y_domain_away_max = d3.max(dataset_reworked_away, function(d) { return d.fgm; });

    x_scale = d3.scaleLinear()
        .domain([x_domain_min, (x_domain_home_max < x_domain_away_max ? x_domain_away_max : x_domain_home_max) * 1.05])
        .range([0, width]);

    y_scale = d3.scaleLinear()
        .domain([y_domain_min, Math.max(y_domain_home_max,y_domain_away_max) * 1.05])
        .range([height, 0]);

    y_scale_home = d3.scaleLinear()
        .domain([y_domain_min, y_domain_home_max * 1.05])
        .range([height, 0]);

    y_scale_away = d3.scaleLinear()
        .domain([y_domain_min, y_domain_away_max * 1.05])
        .range([height,0]);

    y_scale_home_color = d3.scaleLinear()
        .domain([  d3.min(dataset_reworked_home, function(d) { return d.fgm / d.fga; }),
                  d3.max(dataset_reworked_home, function(d) { return d.fgm / d.fga; }) ])
        .range(['#45AFFF','#00297D']);

    y_scale_away_color = d3.scaleLinear()
        .domain([  d3.min(dataset_reworked_away, function(d) { return d.fgm / d.fga; }),
                  d3.max(dataset_reworked_away, function(d) { return d.fgm / d.fga; }), ])
        .range(["#FF8A87",'#691000']);


    //=========================================//
    // 2.4. Container management               //
    //=========================================//
    svg_viz = d3.select('body').append('svg')
        .attr('class',"svg_viz_01")
        .attr('width', svg_width)
        .attr('height', svg_height);

    x_grid_chart = svg_viz.append('g')
        .attr('class',"x_grid_viz_01")
        .attr('width', width)
        .attr('height', padding_bottom)
        .attr("transform", "translate(" + (margin_left + padding_left) + "," + (margin_top + padding_top + height) + ")");

    y_grid_chart = svg_viz.append('g')
        .attr('class',"y_grid_viz_01")
        .attr('width', padding_left)
        .attr('height', height)
        .attr("transform", "translate(" + (margin_left + padding_left) + "," + (margin_top + padding_top) + ")");

    x_axis_chart = svg_viz.append('g')
        .attr('class',"x_axis_viz_01")
        .attr('width', width)
        .attr('height', padding_bottom)
        .attr("transform", "translate(" + (margin_left + padding_left) + "," + (margin_top + padding_top + height) + ")");

    y_axis_left_chart = svg_viz.append('g')
        .attr('class',"y_axis_left_viz_01")
        .attr('width', padding_left)
        .attr('height', height)
        .attr("transform", "translate(" + (margin_left + padding_left) + "," + (margin_top + padding_top) + ")");

    y_axis_right_chart = svg_viz.append('g')
        .attr('class',"y_axis_right_viz_01")
        .attr('width', padding_right)
        .attr('height', height)
        .attr("transform", "translate(" + (margin_left + padding_left + width) + "," + (margin_top + padding_top) + ")");

    chart = svg_viz.append('g')
        .attr('class',"chart_viz_01")
        .attr('width', width)
        .attr('height', height)
        .attr("transform", "translate(" + (margin_left + padding_left) + "," + (margin_top + padding_top) + ")")

    tooltip_chart = d3.select("body").append("div")
        .attr("class", "tooltip_viz_01")
        .text("LOL")
        .style("opacity", 0);


    //=========================================//
    // 2.5. x-axis/grid management             //
    //=========================================//
    x_grid_chart.call(
        d3.axisBottom(x_scale)
            .tickSizeInner(-height)
            .tickSizeOuter(0)
            .tickPadding(20)
    );

    x_axis_chart.call(
        d3.axisBottom(x_scale)
            .tickSizeInner(0)
            .tickSizeOuter(-height)
            .tickPadding(20)
    );


    //=========================================//
    // 2.6. y-axis/grid management             //
    //=========================================//
    y_grid_chart.call(
        d3.axisLeft(y_scale)
            .tickSizeInner(-width)
            .tickSizeOuter(0)
            .tickPadding(20)
    );

    y_axis_left_chart.call(
        d3.axisLeft(y_scale_home)
            .tickSizeInner(0)
            .tickSizeOuter(0)
            .tickPadding(20)
    );

    y_axis_right_chart.call(
        d3.axisRight(y_scale_away)
            .tickSizeInner(0)
            .tickSizeOuter(0)
            .tickPadding(20)
    );


    //=========================================//
    // 2.7. Point management                  //
    //=========================================//
    chart.selectAll()
        .data(dataset_reworked_home)
        .enter().append('circle')
            .attr("r", 4)
            .attr("cx", function(d) {
                return x_scale(d.fga);
            })
            .attr("cy", function(d) {
                return y_scale_home(d.fgm);
            })
            .attr("fill", function(d) {
                return "" + y_scale_home_color( (d.fgm / d.fga).toPrecision(2) ) + "" ;
            })
            .on("mouseover", function(d) {
                d3.select(this).attr('r', 15);
                tooltip_chart.style("opacity", 1)
                    .html(d.nom + "<br/>"  + (d.fgm / d.fga).toPrecision(2) + " %")
                    .style("left", (d3.event.pageX + 20) + "px")
                    .style("top", (d3.event.pageY - 15) + "px");
            })
            .on("mouseout", function(d) {
                d3.select(this).attr('r', 4);
                tooltip_chart.style("opacity", 0);
            });


    chart.selectAll()
        .data(dataset_reworked_away)
        .enter().append('circle')
            .attr("r", 4)
            .attr("cx", function(d) {
                return x_scale(d.fga);
            })
            .attr("cy", function(d) {
                return y_scale_away(d.fgm);
            })
            .attr("fill", function(d) {
                return "" + y_scale_away_color( (d.fgm / d.fga).toPrecision(2) ) + "" ;
            })
            .on("mouseover", function(d) {
                d3.select(this).attr('r', 15);
                tooltip_chart.style("opacity", 1)
                    .html(d.nom + "<br/>"  + (d.fgm / d.fga).toPrecision(2) + " %")
                    .style("left", (d3.event.pageX + 20) + "px")
                    .style("top", (d3.event.pageY - 15) + "px");
            })
            .on("mouseout", function(d) {
                d3.select(this).attr('r', 4);
                tooltip_chart.style("opacity", 0);
            });
}
