require "uri"
require "./web/examples.rb"
require "./version.rb"

# changes when style changes to avoid it being cached
StyleSum = File.read("web/style.css").sum % 1000

raise "generate site using utf-8, not %p" % Encoding.default_external if Encoding.default_external != Encoding::UTF_8

`mkdir ../site` if !Dir.exist? "../site"

def program_url(program, input="")
  program = program.strip.gsub('&amp;','&').gsub('&gt;','>').gsub('&lt;','<')
  input = input.strip.gsub('&amp;','&').gsub('&gt;','>').gsub('&lt;','<')

  "onlineinterpreter.html?" + URI.encode_www_form({
    'program' => program,
    'input' => input,
    'v' => Version
  })
end

subpages = ["Docs","IO","Syntax","Types","Vectorization","Circular Programming","Ops","Examples","Why"]
subpage_urls = subpages.map{|n| n.split.join.downcase }

Dir['docs/*.md'].each{|filename|
  basefile = filename.sub(/\.md$/,'').sub('docs/','')
  md = File.read(filename)

  headers = [["iogii","index"],
             ["Docs"],
             ["Source"],
             ["Quick Ref"],
             ["Online Interpreter"],
             ["Contact"]]

  header = headers.map{|name,url|
    url ||= name.split.join.downcase
    if url != basefile #&& !( subpage_urls.include?(basefile) && name == "Docs" )
      "[#{name}](#{url||name.split.join.downcase}.html)"
    else
      name
    end
  } * " ⸱ " + "<br>\n"

  if subpage_urls.include?(basefile)
    header2 = (subpages-['Docs']).map{|name,url|
      url ||= name.split.join.downcase
      if url != basefile
        "[#{name}](#{url||name.split.join.downcase}.html)"
      else
        name
      end
    } * " ⸱ " + "\n"
    md = header + header2 + md
  else
    md = header + md
  end

def make_example(example,code,input="",pretty_print=false)
  "<div class=\"code-container\">#{example}<a href=\"#{program_url(code,input)}&pp=#{pretty_print.inspect}\" class=\"run-code-icon\">↗️</a>
</div>".gsub(/\n*---\n*/,'<hr>')
end

File.open('t.md','w'){|f|f<<md.gsub(/(\[.*\])\((docs\/)*((.+)\.md)\)/,'\1(\4.html)').gsub('->', '→')}
  html = `markdown.pl < t.md` # https://daringfireball.net/projects/markdown/
  `rm t.md`

  if !filename["quickref.md"]
    html.gsub!('<code>','<code class="inline">')
    html.gsub!('<pre><code class="inline">','<pre><code>')
    html.gsub!(/<pre><code>(.*?)→.*\n?<\/code><\/pre>/) { make_example($&,$1,"",true) }
    html.gsub!(/<pre><code>(.*?)<\/code><\/pre>/m) {
      example = $&
      if $1 =~ /\A(.*?)---(.*)\Z/m
        fst = $1
        rest = $2
        if $2 =~ /(.*?)---.*/m
          make_example(example,$1,fst)
        else
          make_example(example,fst)
        end
      else
        example
      end
    }
  end

  if filename["source"]
    html.gsub!('VERSION',Version)
  end

  html.gsub!('<p>$quickref</p>', `ruby web/quickref.rb`)
  html.gsub!('<p>$interpreter</p>'){ File.read('web/online_interpreter_body.html').gsub('VERSION',Version).gsub('$iogii') { `ruby web/mk1file.rb webmain.rb`.gsub(/[`$\\]/){'\\'+$&} } }
  html.gsub!("$options"){
    Examples.take_while{|name,_|
      !name.include?("test")
    }.map{|name,prog,input,expected|
      "<option value=\"#{program_url(prog,input)}\">#{name}</option>"
    }*"\n"
  }

  html.sub!(/<p>/,'<p class="noprint">') # don't print the heading links

  html.sub!(/<h1>(.*?)<\/h1>/,filename["quickref.md"] ? '<h1 class="noprint">\1</h1>' : '\&')
  title = $1
  title = "iogii" if filename == "index.md"

  def showid(name)
    name = name.downcase.tr'^a-z0-9',''
    name.empty? ? "" : " id=\"#{name}\""
  end

  html.gsub!(/<(h[1-3])>(.*?)<\/\1>/){"<#$1#{showid($2)}>#$2</#$1>"}

  if title.nil?
    puts 'skipping '+filename
    return
  end

  # device width thing is to stop mobile browsers from scaling the page weird, messing up the header links
  File.open('../site/'+basefile+'.html','w'){|f|f<<'<!DOCTYPE html>
<html lang="en"><!-- This file is automatically generated from generate_site.rb by reading '+filename+' --><head><meta name="viewport" content="width=device-width, initial-scale=1"><meta charset="utf-8"><title>'+title+'</title><link rel="stylesheet" href="style.css?id=' + StyleSum.to_s + '"><link rel="icon" href="ig.svg" type="image/svg+xml"></head><body>
<div id="content">'+html+'</div>
</body></html>'}
}

`cp web/style.css web/ig.svg web/snapshot.html ../site/`
