#!/usr/bin/ruby
require File.join(File.dirname(__FILE__), 'common')
require 'cgi'

class CGI
  def redirect( where )
    print self.header( { 'Status' => '302 Moved', 'location' =>
where } )
  end
end

cgi = CGI.new('html4')

if File.exist? CHAIN_FILE
  mc = YAML.load open(CHAIN_FILE)
else
  raise "Whoa hey there"
end



cache = YAML.load open(CACHE_FILE)

def splice_cache c, start=""
  a = c.to_a[rand(c.size)]
  b = c.to_a[rand(c.size)]

  beginning, crap, join = split_line a
  crap, ending, end_join = split_line b

  if start == ""
    return beginning + join + ending
  else
    return start + end_join + ending
  end
end

def split_line a
  joiner = a[/:|--|,|;/]
  if joiner then
    joiner << " "
    a1, a2 = a.split(/:|--|,|;/,2)
  else
    s = (a.length / 2) + 5 - rand(10)
    s = a.index(" ", s)
    s ||= a.index(" ")
    a1 = a[0..s-1]
    a2 = a[s+1..-1]
    joiner = " "
  end
  return [a1, a2, joiner]
end

seed = if not cgi["seed"] or cgi["seed"] == ""
  Time.new.tv_sec.to_i
else
  cgi["seed"].to_i
end

srand seed

headlines = if cgi["start"] and cgi["start"] != ""
  (1..10).map do
    if rand(10) > 5
      "<li>" + mc.generate_sentence(cgi["start"].split(" "))
    else
      "<li><b>" + splice_cache(cache, cgi["start"]) + "</b>"
    end
  end.to_set
else
  (1..10).map do
    if rand(10) > 5
      "<li>" + mc.generate_sentence 
    else
      "<li><b>" + splice_cache(cache) + "</b>"
    end
  end.to_set
end


cgi.out do
<<END
<html>
<head>
<style>
body, td, th, textarea, select, h2, h3, h4, h5, h6 {font: 12px/1.25em arial, sans-serif;}
ul li {padding:0 0 3px 8px;font-weight:normal;font-size:12px;line-height:15px;margin:0;color:#333388;}
</style>
</head>
<body>
<h2>FAKE CNN 2 LAZY 2 STYLE ITSELF DOT COM</h2>
<p><a href="?seed=#{seed}&start=#{cgi["start"]}">link to this set</a> (temporary!)</p>
<form method="get"><input type='submit' value="RANDOM"/></form>
<form method="get">headline start: <input name='start' value='#{cgi["start"]}'/> <input type='submit' value="YES"/></form><br/>
<ul>
#{headlines.to_a.join("\n")}
</ul>
</body>
</html>
END
end



