ig.module(
	'game.main'
)
.requires(
  //'impact.debug.menu',
	'impact.game',
	'impact.font',

	'game.entities.ball',
	'game.entities.paddle-enemy',
	'game.entities.paddle-player',

  'game.entities.namefield',

	'game.levels.level1'
)
.defines(function() {
  RunningGame = ig.Game.extend({
    font: new ig.Font('media/lcddot.font.png'),

    pauseDialogAlpha: 0,
    pauseDialog: new ig.AnimationSheet('media/pause_screen.png', 624, 384),
    pauseDialogAnim: null,
    showPause: false,
    
    clearColor: null,

    init: function() {
      ig.input.unbindAll();
      ig.global.lifes = 4; // increase this to 3
      ig.global.score = 0;

      // Menu navigation
      ig.input.bind(ig.KEY.ESC, 'escape');
      ig.input.bind(ig.KEY.ENTER, 'enter');

      // Game navigation
      ig.input.bind(ig.KEY.UP_ARROW, 'up');
      ig.input.bind(ig.KEY.DOWN_ARROW, 'down');
      ig.input.bind(ig.KEY.T, 'force-top');
      ig.input.bind(ig.KEY.B, 'force-bottom');

      // vim goodness
      ig.input.bind(ig.KEY.K, 'up');
      ig.input.bind(ig.KEY.J, 'down');

      // Gamer style
      ig.input.bind(ig.KEY.W, 'up');
      ig.input.bind(ig.KEY.S, 'down');

      // init graphics
      this.pauseDialogAnim = new ig.Animation( this.pauseDialog, 0, [0] )

      // init music
      ig.music.add('media/sounds/DST-AngryRobotIII.ogg');
      ig.music.add('media/sounds/DST-2ndBallad.ogg');
      ig.music.random = true;
      ig.music.loop = true;
      ig.music.volume = 0.3;
      ig.music.play();

      // Load the level
      this.loadLevel(LevelLevel1);
    },

    update: function() {
      // User is in the pause menu
      if (this.showPause) {
        if (ig.input.pressed('escape')) {
          ig.system.setGame(StartScreen);
          return;
        }

        if (ig.input.pressed('enter')) {
          this.showPause = false;
          this.pauseDialogAlpha = 0;
          return;
        }
      }

      // The game is over
      if (ig.global.lifes == 0) {
        ig.system.setGame(ScoreboardScreen);
      }

      // The User want back to the main menu inside a running game
      if (ig.input.pressed('escape')) {
        this.showPause = true;
      }

      // The game is running
      if (!this.showPause) this.parent();
    },

    draw: function() {
      ig.system.context.clearRect( 0 ,0, ig.system.realWidth, ig.system.realHeight );
		  this.parent(); // Draw entries and background
      this.font.draw(ig.global.score, 390, 8, ig.Font.ALIGN.RIGHT);

      if (this.showPause) {
        if(this.pauseDialogAlpha < 1) {
          this.pauseDialogAlpha += .1;
          if(this.pauseDialogAlpha > 1) this.pauseDialogAlpha = 1;

          this.pauseDialogAnim.alpha = this.pauseDialogAlpha;
        }
        this.pauseDialogAnim.draw(0, 0);
      }
	  }
  });

  ScoreboardScreen = ig.Game.extend({
    scoreoid: {
      api_key: 'd1011f8f6776a10f7a5d87eaa86c43c8d2ffb9dc',
      game_id: '642fc6c1e8',
      response: 'json'
    },

    font: new ig.Font( 'media/lcddot.font.png' ),
    fontSmall: new ig.Font( 'media/lcddot.small.font.png' ),
    fontSmallGrey: new ig.Font( 'media/lcddot.small.grey.font.png' ),
    
    backgroundInput: new ig.Image('media/highscore_input_screen.png'),
    background: new ig.Image('media/highscore_screen.png'),
    nameField: null,
    clearColor: null,

    init: function() {
      ig.input.bind(ig.KEY.ENTER, 'submit-score');
      ig.input.bind(ig.KEY.ESC, 'main-menu');
      this.nameField = ig.game.spawnEntity(EntityNameField, 363, 219);
      this.loadScores();
    },

    update: function() {
      if (ig.input.pressed('main-menu')) {
        ig.system.setGame(StartScreen);
      }

      if (ig.input.pressed('submit-score') && this.nameField !== null) {
        this.saveScore(this.nameField.name(), ig.global.score, function(context) {
          setTimeout(function() { context.loadScores(); }, 2000);
        });
        this.nameField.kill();
        this.nameField = null;
      }
      this.parent();
    },

    loadScores: function() {
      ig.global.scores = undefined;
      data = $.extend({}, {
        order: 'desc',
        order_by: 'score',
        limit: 10
      }, this.scoreoid);
      $.post('https://www.scoreoid.com/api/getBestScores', data, function(data) {
        ig.global.scores = data;
      });
    },

    saveScore: function(username, score, cb) {
      data = $.extend({}, {
        score: score,
        username: username
      }, this.scoreoid);
      $.post('https://www.scoreoid.com/api/createScore', data, cb(this));
    },

    draw: function() {
      ig.system.context.clearRect( 0 ,0, ig.system.realWidth, ig.system.realHeight );
      this.parent();
      if (this.nameField !== null) this.backgroundInput.draw(0, 0);
      else this.background.draw(0, 0);

      // Draw the current highscore if its loaded
      var num = 1;
      if (ig.global.scores !== undefined) {
        var ypos = 50;
        var font = this.fontSmall;

        for (var i=0; i<ig.global.scores.length; i++) {
          var score = ig.global.scores[i];

          if(num <= 3) font = this.fontSmall;
          else font = this.fontSmallGrey;

          font.draw(num, 60, ypos, ig.Font.ALIGN.CENTER);
          font.draw(score.Score.score, 210, ypos, ig.Font.ALIGN.RIGHT);
          font.draw(score.Player.username, 250, ypos, ig.Font.ALIGN.LEFT);

          ypos += 30;
          num++;
        }
      }

      if (this.nameField !== null) this.nameField.draw();
      this.font.draw(ig.global.score, 524, 112, ig.Font.ALIGN.RIGHT);
    }
  });

  StartScreen = ig.Game.extend({
    background: new ig.Image('media/main_screen.png'),
    clearColor: null,

    init: function() {
      ig.input.bind(ig.KEY.ENTER, 'start-game');
      ig.input.bind(ig.KEY.H, 'highscore'); // XXX: Just for debug purpose
    },

    update: function() {
      if (ig.input.pressed('start-game')) {
        ig.system.setGame(RunningGame);
      }

      // XXX: Just for debug purpose
      if (ig.input.pressed('highscore')) {
        ig.global.score = Math.floor(Math.random()*1000)*1;
        ig.system.setGame(ScoreboardScreen);
      }
      this.parent();
    },

    draw: function() {
      ig.system.context.clearRect( 0 ,0, ig.system.realWidth, ig.system.realHeight );
      this.parent();
      this.background.draw(0, 0);
    }
  });

  // Start the Game with 60fps, a resolution of 640x400 (16:10), scaled
  // up by a factor of 2
  ig.main( '#canvas', StartScreen, 60, 624, 384, 1 );
});

