/** 
 *  Yudit Unicode Editor Source File
 *
 *  GNU Copyright (C) 1997-2023  Gaspar Sinai <gaspar@yudit.org>  
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License, version 2,
 *  dated June 1991. See file COPYYING for details.
 *
 *  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, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "swindow/SAwt.h"
#include "swidget/SIcon.h"
#include "stoolkit/SHashtable.h"

typedef SHashtable<SImage> SImageCache;
static SImageCache* imageCache=0;

static int scaleInt (int value) {
    return (int) (0.9 + SAwt::getScale() * value);
}

SIcon::SIcon (const SImage& _image) : image (_image)
{
  preferredSize = SDimension (
    scaleInt(image.getWidth()),
    scaleInt (image.getHeight()));
}

/**
 * Create an icon from name. previously it should
 * be added with the static put method
 */
SIcon::SIcon (const SString& _name) : image (1, 1, 1)
{
  preferredSize = SDimension (
    scaleInt(image.getWidth()),
    scaleInt (image.getHeight()));

  if (imageCache == 0) imageCache = new SImageCache();
  const SImage* im = imageCache->get (_name);
  if (im==0)
  {
    fprintf (stderr, "SIcon::SIcon: can not find image %*.*s\n", SSARGS(_name));
  }
  else
  {
    image = *im;
  }
}

SIcon::~SIcon ()
{
}

void
SIcon::redraw (SCanvas* canvas, int x, int y, 
       unsigned int width, unsigned int height)
{
  redraw (canvas);
}

void
SIcon::redraw (SCanvas* canvas)
{
  SVGBase * svgBase = image.getSVGBase();
  if (svgBase) {
    canvas->pushmatrix();
    canvas->scale(SAwt::getScale(), SAwt::getScale());
    canvas->translate (getLocation().x-SAwt::getScale()*getLocation().x,
        getLocation().y-SAwt::getScale()*getLocation().y);
    svgBase->setCanvas (canvas, background);
    svgBase->render(getLocation().x, getLocation().y);
    canvas->popmatrix();
  } else {
    canvas->putImage (getLocation().x, getLocation().y, image);
  }
}

void
SIcon::put (const SString& name, const SImage& image)
{
  if (imageCache == 0) imageCache = new SImageCache();
  imageCache->put (name, image);
}

void
SIcon::remove (const SString& name)
{
  if (imageCache == 0) imageCache = new SImageCache();
  imageCache->remove (name);
}

bool
SIcon::exists (const SString& name)
{
  if (imageCache == 0) imageCache = new SImageCache();
  return (imageCache->get (name) != 0);
}

void
SIcon::setBackground (const SColor& bg)
{
  SComponent::setBackground (bg);
  background = bg;
}

const SImage&
SIcon::getImage () const
{
  return image;
}

