import * as d3 from "d3";

export interface Data {
  date: Date;
  km: number;
}

if (sessionStorage.getItem("userStats")) {
  const data = JSON.parse(
    sessionStorage.getItem("userStats") || "{}",
  ) as Data[];

  if (data.length >= 2) {
    const margin = { top: 20, right: 20, bottom: 50, left: 50 };
    const width: number = 960 - margin.left - margin.right;
    const height: number = 500 - margin.top - margin.bottom;

    data.forEach((d: Data) => {
      d.date = <Date>new Date(d.date);
      d.km = +d.km;
    });

    const x = d3
      .scaleTime()
      .domain(<[Date, Date]>d3.extent(data, (d: Data) => d.date))
      .range([0, width]);

    const y = d3
      .scaleLinear()
      .domain([0, Number(d3.max(data, (d: Data) => d.km))])
      .range([height, 0]);

    const line = d3
      .line<Data>()
      .x((d: Data) => x(d.date))
      .y((d: Data) => y(d.km));

    const svg = d3
      .select("#container")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .call(responsivefy)
      .append("g")
      .attr("transform", `translate(${margin.left},${margin.top})`);

    svg.append("path").data([data]).attr("class", "line").attr("d", line);

    svg
      .append("g")
      .attr("transform", `translate(0,${height})`)
      .call(d3.axisBottom(x));

    svg.append("g").call(d3.axisLeft(y));
  }
}

function responsivefy(svg: any) {
  const container = d3.select(svg.node().parentNode);
  const width = parseInt(svg.style("width"), 10);
  const height = parseInt(svg.style("height"), 10);
  const aspect = width / height;

  svg
    .attr("viewBox", `0 0 ${width} ${height}`)
    .attr("preserveAspectRatio", "xMinYMid")
    .call(resize);

  d3.select(window).on("resize." + container.attr("id"), resize);

  function resize() {
    const w = parseInt(container.style("width"));
    svg.attr("width", w);
    svg.attr("height", Math.round(w / aspect));
  }
}
