library("jsonlite")

# Load Vega theme config
theme <- fromJSON("theme.json")

# Declare global JS var for Vega theme
cat(paste('<script>var theme = ', toJSON(theme, auto_unbox = TRUE), ';</script>', sep = ""))
library("jsonlite")
library("purrr", warn.conflicts = FALSE)

# Use iris dataset, rename columns for JS
data = iris %>%
  set_names(~ str_camel_case(.))

# Declare global JS var for Vega data
cat(paste('<script>var data = ', toJSON(data), ';</script>', sep = ""))
// Generate Vega-Lite spec
var spec = finch
  .vl(data)
  .config(theme)
  .circle()
  .x('petalLength')
  .y('sepalLength')
  .color('species', 'nominal')
  .spec;

// Declare Vega embed config
var opts = {
  actions: false,
  renderer: 'canvas'
};

// Embed visualisation
vegaEmbed('#scatterplot', spec, opts);
var spec = finch
  .vl(data)
  .config(theme)
  .width(150)
  .height(150)
  .bar()
  .x('sepalLength', 'q', {
    bin: true,
    title: 'sepalLength'
  })
  .y(null, 'q', {aggregate: 'count', title: 'count'})
  .tooltip(null, 'q', {aggregate: 'count'})
  .column('species', 'n')
  .spec;

vegaEmbed('#faceted-plot', spec, {actions: false});
var spec = finch
  .vl(data)
  .config(theme)
  .repeat(
    {
      row: ['sepalLength', 'sepalWidth', 'petalLength', 'petalWidth'],
      column: ['sepalLength', 'sepalWidth', 'petalLength', 'petalWidth']
    },
    finch
      .vl()
      .width(100)
      .height(100)
      .circle()
      .x({repeat: 'column'}, 'q')
      .y({repeat: 'row'}, 'q')
      .color('species', 'n')
  ).spec;

vegaEmbed('#repeated-plot', spec, {actions: false});
// Fit data to polynomial curve
var fitData = regression
  .polynomial(
    data.map(function(d) {
      return [d.petalLength, d.sepalLength];
    })
  )
  .points.map(function(d) {
    return {x: d[0], y: d[1]};
  });

var spec = finch
  .vl()
  .config(theme)
  .layer(
    finch
      .vl(data)
      .circle()
      .x('petalLength')
      .y('sepalLength')
      .color(null, null, {value: 'blue'}),
    finch
      .vl(fitData)
      .line()
      .x('x', null, {axis: null})
      .y('y', null, {axis: null})
      .color(null, null, {value: 'red'})
  )
  .tooltip([
    {field: 'petalLength', type: 'q'},
    {field: 'sepalLength', type: 'q'}
  ])
  .spec;

vegaEmbed('#polynomial-fit', spec, {actions: false});