extern crate piston_window;
extern crate piston;
extern crate find_folder;
extern crate getopts;
extern crate time;
extern crate rustc_serialize;
extern crate crypto;
#[macro_use] extern crate lazy_static;
extern crate regex;
use getopts::Options;
use std::env;
use std::process;
use std::ops;
use piston::input::*;
use piston::event_loop::*;
use std::sync::mpsc::channel;
use std::thread;

mod board;
mod lang;
mod play;
mod model;
mod view;
mod control;
mod terrain;

fn main() {
   let args: Vec<String> = env::args().collect();

   let mut opts = Options::new();
   opts.optflag("r", "record", "record output in mpeg");
   opts.optopt("w", "width", "board width", "200");
   opts.optopt("h", "height", "board height", "200");
   opts.optopt("g", "game", "game type", "rogue");

   let matches = match opts.parse(&args[1..]) {
      Ok(m) => { m }
      Err(f) => { panic!(f) }
   };


   use piston_window::*;

   let mut ws = WindowSettings::new(
       "Red Yellow Blue",
       [9999, 9999]
   );
   let mut window: PistonWindow = ws.build().unwrap();
   window.set_lazy(true);

   let mut m: model::GameState = model::GameState::new();
   let mut v: model::WindowState = model::WindowState::new(&window);

   let mut events = Events::new(EventSettings::new().lazy(false));
   events.set_ups(10);
   events.max_fps(100);
   let mut last_click = time::precise_time_s();
   let mut last_press = time::precise_time_s();

   while let Some(e) = events.next(&mut window) {
      if let Some(Button::Mouse(button)) = e.press_args() {
         v.clicked = Some(format!("{:?}", button));
         last_click = time::precise_time_s();
      } else if (time::precise_time_s() - last_click)>0.1 {
         v.clicked = None;
      }
      if let Some(Button::Keyboard(key)) = e.press_args() {
         let s = format!("{:?}", key);
         v.press_held.insert(s.clone(), s.clone());
         v.pressed = Some(s);
         last_press = time::precise_time_s();
      } else if (time::precise_time_s() - last_press)>0.1 {
         v.pressed = None;
      }
      if let Some(Button::Keyboard(key)) = e.release_args() {
         let c = format!("{:?}", key);
         v.press_held.remove(&c);
      }
      e.mouse_cursor(|x, y| {
         v.cursor = [x, y];
      });

      control::react(&mut m, &mut v);
      view::render(&mut m, &mut v, &mut window, &e);
   }
}

