#include "empire.h"

bool _button::mouseover()
{
  int mx;
  int my;
  mx = mouse_x;
  my = mouse_y;
  if ((mx >= x) && (mx <= x + w))
  {
    if ((my >= y) && (my <= y + h))
    {
      return true;
    }
  }
  return false;
}

bool _button::mousedown()
{
  if (mouseover())
  {
    if (mouse_b & 1)
    {
      return true;
    }
  }
  return false;
}

bool _button::clicked()
{
	if (clickable)
	{
		if (click)
		{
			if ((!mousedown()) && (mouseover()))
			{
				click = false;
				return true;
			}
		}
		else
		{
      if (mousedown())
		  {
			  click = true;
			}
		}
  }
  return false;
}

void _button::draw()
{
  if ((picture == NULL) || (!picture->IsValid()))
  {
    if (mousedown() == 0)
    {
      switch(type)
      {
        case 0:  //standard button
          if (mouseover())
          {
            buffer_rectrounded(x, y, x + w, y + h, WHITE, 0.7);
          }
          else
          {
            buffer_rectrounded(x, y, x + w, y + h, WHITE, 0.4);
          }
          buffer_textout_ex(normal, text, x + (w / 2) - (textw / 2), y + (h / 2) - 5, BLACK);
          break;
        case 1:  //larger text, no background
          buffer_textout_ex(big, text, x, y, WHITE, texta);
          break;
      }
    }
    else
    {
      switch(type)
      {
        case 0:
          buffer_rectrounded(x, y, x + w, y + h, WHITE, 0.7);
          buffer_textout_ex(normal, text, x + (w / 2) - (textw / 2) + 1, y + (h / 2) - 4, BLACK);
          break;
        case 1:
          buffer_textout_ex(big, text, x, y, WHITE, texta);
          break;
      }
    }
  }
  else
  {
    buffer_blit_clipped(picture, x, y, 0, 0, w, h);
  }
}

void _button::check()
{
  draw();
  if (type == 1)
  {
    if (mouseover())
    {
      if (texta < 1.0)
      {
        texta += 0.05;
      }
    }
    else
    {
      if (texta > 0.5)
      {
        texta -= 0.05;
      }
    }
  }
  if (clickable)
  {
    if (mousedown())
    {
      if (!sound)
      {
        play_sound(S_CLICK);
        sound = true;
      }
    }
    else
    {
      sound = false;
    }
  }
}

void _button::init(int ix, int iy, int iw, int ih, int itype)
{
  init(ix, iy, iw, ih, "", NULL, itype);
}

void _button::init(int ix, int iy, int iw, int ih, string itext, int itype)
{
  init(ix, iy, iw, ih, itext, NULL, itype);
}

void _button::init(int ix, int iy, int iw, int ih, string itext, Bitmap *ipicture, int itype)
{
  x = ix;
  y = iy;
  w = iw;
  h = ih;
  type = itype;
  text = itext;
  if (type == 0)
  {
    textw = normal.Width(text);
    texta = 1.0;
  }
  else if (type == 1)
  {
    textw = big.Width(text);
    w = textw + 5;
    texta = 0.5;
  }
  picture = ipicture;
  click = false;
  sound = false;
  clickable = true;
}

string _button::get_text()
{
  return text;
}
