/*
    Bazoo_worms the game
    Copyright (C) 2011  Pavel Prochazka

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "MG_lib.h"
#include <assert.h>
#include  "WRMS_include.h"

static SPRITE *_landscape = NULL;

static SDL_Surface *
WRMS_copy_surf (SDL_Surface * s, unsigned int flags)
{
  assert (s != NULL);
  SDL_Surface *out = surface_new (s->w, s->h, flags);
  if (out)
    {
      SDL_BlitSurface (s, NULL, out, NULL);
    }
  return out;
}

void
WRMS_landscape_free_surface ()
{
  SPRITE *l = WRMS_landscape_get ();
  if (!l)
    return;

  SDL_FreeSurface (l->img);
}

SPRITE *
WRMS_landscape_build (const char *path)
{
  SDL_Surface *s = MG_get_img (path);

  if (!s)
    return NULL;

  SDL_Surface *copy_s = WRMS_copy_surf (s, SDL_SRCCOLORKEY);
  SPRITE *out = MG_make_sprite (copy_s, NULL);	//,1);
  SDL_Rect wrld = WRMS_WORLD_SCREEN;	//MG_get_machine()->view_rect;

  out->type = LANDSCAPE;

  _landscape = out;

  MG_move_sprite (out, wrld.w / 2 - out->dest.w / 2, wrld.h - out->dest.h);

  SDL_Rect v = MG_get_machine ()->view_rect;

  MG_install_callback (out, "on_destroy", WRMS_landscape_free_surface);

  v.y = out->dest.y;
  v.x = out->dest.x;

  MG_set_view_rect (v);

  return out;
}


SPRITE *
WRMS_landscape_get ()
{
  return _landscape;
}

SPRITE *
WRMS_build_sea (const char *path)
{
  SPRITE *out = MG_make_sprite (MG_get_img (path), NULL);
  SPRITE *landscape = WRMS_landscape_get ();

  out->type = WATER;

  MG_move_sprite (out, 0,
		  (landscape->dest.y + landscape->dest.h) - out->dest.h);
  return out;
}
