#!/usr/bin/ruby

require 'wunderbar'
require 'json'
require 'addressable/uri'

_html do
  _h1 "URI vs URL"
  _style %{
    table {
      border-collapse: collapse;
    }

    table, th, td {
      border: 1px solid black;
    }

    th, td {
      min-width: 8em
    }

    th {
      background-color: LightBlue
    }
  }

  normalized = _.params.include? 'normalized'
  if normalized
    _h2 'Normalized'
  else
    _h2 'Unnormalized'
  end

  JSON.parse(File.read('urltestdata.json')).each do |test|
    input = test.delete('input')
    base = test.delete('base')
    test['user'] = test.delete('username')

    begin
      uri = Addressable::URI.parse(input.strip)
      uri = Addressable::URI.join(base, uri)
      uri = uri.normalize if normalized
    rescue Addressable::URI::InvalidURIError
      uri = Addressable::URI.parse('')
    end

    diffs = []
    test.each do |attr, expected|
      value = uri.send(attr).to_s
      value = "##{value}" if attr=='fragment' and not value.empty?
      value = "?#{value}" if attr=='query' and not value.empty?

      diffs << [attr, value, expected.to_s] if value != expected.to_s
    end

    unless diffs.empty?
      _h3_ "{input: #{input.inspect}, base: #{base.inspect}}"
      _table do
        _tr do
          _th 'property'
          _th 'IETF URI'
          _th 'WHATWG URL'
        end
        diffs.each do |attr, uri, url|
          _tr do
            _td attr
            _td uri.inspect
            _td url.inspect
          end
        end
      end
    end

  end
end