import { Spec } from 'vega';

export const spec: Spec = {
  $schema: 'https://vega.github.io/schema/vega/v5.json',
  width: 800,
  padding: 5,

  config: {
    title: { fontSize: 14 }
  },

  title: {
    text: 'Seattle Annual Temperatures',
    anchor: 'start',
    offset: 4
  },

  signals: [
    { name: 'rangeStep', value: 25 },
    { name: 'height', update: 'rangeStep * 24' }
  ],

  data: [
    {
      name: 'temperature',
      url: 'data/seattle-weather-hourly-normals.csv',
      format: { type: 'csv', parse: { temp: 'number', date: 'date' } },
      transform: [
        { type: 'formula', as: 'hour', expr: 'hours(datum.date)' },
        {
          type: 'formula',
          as: 'date',
          expr: 'datetime(year(datum.date), month(datum.date), date(datum.date))'
        }
      ]
    }
  ],

  scales: [
    {
      name: 'row',
      type: 'band',
      domain: [
        6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5
      ],
      range: { step: { signal: 'rangeStep' } }
    },
    {
      name: 'x',
      type: 'time',
      domain: { data: 'temperature', field: 'date' },
      range: 'width'
    },
    {
      name: 'y',
      type: 'linear',
      zero: false,
      domain: { data: 'temperature', field: 'temperature' },
      range: [{ signal: 'rangeStep' }, 1]
    }
  ],

  axes: [
    { orient: 'bottom', scale: 'x', domain: false, title: 'Month', format: '%b' },
    {
      orient: 'left',
      scale: 'row',
      domain: false,
      title: 'Hour',
      ticks: false,
      encode: {
        labels: {
          update: {
            text: {
              signal:
                "datum.value === 0 ? 'Midnight' : datum.value === 12 ? 'Noon' : datum.value < 12 ? datum.value + ':00 am' : (datum.value - 12) + ':00 pm'"
            }
          }
        }
      }
    }
  ],

  marks: [
    {
      type: 'group',
      from: {
        facet: {
          name: 'hour',
          data: 'temperature',
          groupby: 'hour'
        }
      },
      encode: {
        enter: {
          x: { value: 0 },
          y: { scale: 'row', field: 'hour' },
          width: { signal: 'width' },
          height: { signal: 'rangeStep' }
        }
      },
      marks: [
        {
          type: 'area',
          from: { data: 'hour' },
          encode: {
            enter: {
              x: { scale: 'x', field: 'date' },
              y: { scale: 'y', field: 'temperature' },
              y2: { signal: 'rangeStep' }
            }
          }
        }
      ]
    }
  ]
};
