let _width = $(window).width();
let _height = $(window).height();
let width = 1 * _width;
let height = 1 * _height;

let x_attr = 'date';
let y_attr =  'close';
let fontFamily;
let categories;

function set_ui() {
    // 设置字体
    let ua = navigator.userAgent.toLowerCase();
    fontFamily = "Khand-Regular";
    if (/\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(ua)) {
        fontFamily = "PingFangSC-Regular";
    }
    d3.select("body")
        .style("font-family", fontFamily);
}

function draw_main() {
    let padding = {'left': 0.1*width, 'bottom': 0.1*height, 'top': 0.1*height, 'right': 0.1*width};
    let svg = d3.select('#container')
        .select('svg')
        .attr('width', width)
        .attr('height', height);

    // title
    svg.append('g')
        .attr('transform', `translate(${padding.left+(width-padding.left-padding.right)/2}, ${padding.top*0.7})`)
        .append('text')
        .attr('class', 'title')
        .text('Choropleth for Unemployment Rate by County in America');

    // color scheme
    let n = 9;
    let interval = 0.01;
    let domain = [interval, interval*10];
    let color = d3.scaleQuantize()
        .domain(domain)
        .range(d3.schemeBlues[n]);

    // map
    let map_width = 1014;
    let map_height = 593;

    // county
    map = svg.append('g')
        .attr('transform', `translate(${width/2-map_width*0.45},${height/2-map_height/2})`);
    
    map.selectAll('path')
        .data(topojson.feature(map_data, map_data.objects.counties).features.filter(d => ids.indexOf(d.id) != -1))
        .enter().append('path')
        .attr('class', 'county')
        .attr('d', d3.geoPath())
        .attr('fill', d => {
            let id = d.id;
            let data = id2data[id];
            let rate = data['rate'];  

            return color(percent2float(rate));
        })
        .on('mouseover', (e, d) => {
            // show a tooltip
            let id = d.id;
            let data = id2data[id];
            let state = data['state'];
            let county = data['county'];
            let rate = data['rate'];

            let content = '<table><tr><td>State</td><td>' + state + '</td></tr>' 
                + '<tr><td>County</td><td>'+ county + '</td></tr>'
                + '<tr><td>Unemployment Rate</td><td>'+ rate + '%</td></tr></table>';
            
            // tooltip
            d3.select('#tooltip')
                .html(content)
                .style('left', (e.x + 5) + 'px')
                .style('top', (e.y + 5)+ 'px')
                .style('visibility', 'visible');
        })
        .on('mouseout', (e, d) => {
            d3.select('#tooltip')
                .style('visibility', 'hidden');
        })

    // state
    map.append('path')
        .datum(topojson.mesh(map_data, map_data.objects.states, (a, b) => a !== b))
        .attr('fill', 'none')
        .attr('stroke', 'white')
        .attr('stroke-linejoin', 'round')
        .attr('d', d3.geoPath());

    // color legend
    rect_width = map_width*0.02;
    rect_height = rect_width/3;
    legend = svg.append('g')
        .attr('transform', `translate(${width/2+map_width*0.4-rect_width*n}, ${height/2-map_height*0.4})`);

    g1 = legend.append('g')
        .selectAll('g')
        .data(d3.range(1, 10))
        .enter().append('g')
        .attr('transform', (d, i) => `translate(${i*rect_width},${0})`);
        
    g1.append('rect')
        .attr('width', rect_width)
        .attr('height', rect_height)
        .attr('fill', (d, i) => color(0.01*(i+1)));

    g2 = legend.append('g')
        .selectAll('g')
        .data(d3.range(2, 10))
        .enter().append('g')
        .attr('transform', (d, i) => `translate(${(i+1)*rect_width},${0})`);

    g2.append('line')
        .attr('x1', 0)
        .attr('y1', 0)
        .attr('x2', 0)
        .attr('y2', rect_height*1.3)
        .attr('stroke', 'rgb(50,50,50)')
        .attr('stroke-opacity', 0.8);
    g2.append('text')
        .attr('x', 0)
        .attr('y', rect_height*2.6)
        .attr('text-anchor', 'middle')
        .attr('font-size', 10)
        .text(d => d);

    legend.append('text')
        .attr('dy', '-0.3rem')
        .attr('font-weight', 'bold')
        .attr('font-size', 11)
        .text('Unemployment rate (%)');
    
}

function main() {
    d3.json(map_file).then(function(map) {
        d3.csv(data_file).then(function(DATA) {

            // topojson map file
            map_data = map;

            // statistics
            data = DATA;
            data.forEach(d => {
                id2data[d.id] = d;
                ids.push(d.id);
            })
            console.log('map data', map_data);
            console.log('data', data);

            set_ui();
            draw_main();
        })        
    })

}

main()