#include <iostream>
#include "tt.hh"
using namespace std;

tetris_board tb;

void print_board() {
  // Print the current situation
  std::cout << "Current board:" << std::endl;
  for (unsigned int i = 0; i < tb.get_board().size(); ++i) {
    std::cout << "  |" << tb.get_board()[i] << "|" << std::endl;
  }
  std::cout << std::endl;
  std::cout << "Next piece:" << std::endl;
  for (int i = 0; i < 4; ++i) {
    for (int j = 0; j < 4; ++j)
      std::cout << tb.get_next_piece().piece[i][j];
    std::cout << std::endl;
  }
  std::cout << std::endl;
}

void do_down() {
  int row;
  switch (tb.down(row)) {
  case 0:
    std::cout << "New piece created" << std::endl;
    std::cout << "Cleared " << row << " rows" << std::endl;
    break;
  case 1:
    std::cout << "Game over" << std::endl;
    std::cout << "Cleared " << row << " rows" << std::endl;
    break;
  }
}

void do_resize() {
  int w, h;
  bool done;
  do {
    done = true;
    std::cout << "Width? ";
    std::cin >> w;
    std::cout << "Height? ";
    std::cin >> h;
    try {
      tb.resize(w, h);
    } catch (tetris_board::CreateBoardError) {
      std::cout << "Can't initialize board" << std::endl;
      done = false;
    }
  } while (!done);
}

int main() {
  // Start the game
  bool done = false;
  while (!done) {
    print_board();
    // Ask for a command
    std::cout << "Command (lracdNRq): ";
    char cmd;
    std::cin >> cmd;
    // Perform that command
    switch (cmd) {
    case 'l':
      if (!tb.shift_left())
	std::cout << "Failed" << std::endl;
      break;
    case 'r':
      if (!tb.shift_right())
	std::cout << "Failed" << std::endl;
      break;
    case 'a':
      if (!tb.rot_ccw())
	std::cout << "Failed" << std::endl;
      break;
    case 'c':
      if (!tb.rot_cw())
	std::cout << "Failed" << std::endl;
      break;
    case 'd':
      do_down();
      break;
    case 'N':
      // This might end up requiring a resize,
      // since the size might have been 4x1 with a straight line there,
      // and when the board is restarted, an exception might results.
      try {
	tb.restart();
	break;
      } catch (tetris_board::CreateBoardError) {
	std::cout << "Need resizing." << std::endl;
      }
      // Fall-through
    case 'R':
      do_resize();
      break;
    case 'q':
      done = true;
    }
  }
}

