/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2003-2006 RSSOwl Development Team                                  **
 **   http://www.rssowl.org/                                                 **
 **                                                                          **
 **   All rights reserved                                                    **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the Eclipse Public License 1.0 which accompanies this     **
 **   distribution, and is available at:                                     **
 **   http://www.rssowl.org/legal/epl-v10.html                               **
 **                                                                          **
 **   A copy is found in the file epl-v10.html and important notices to the  **
 **   license from the team is found in the textfile LICENSE.txt distributed **
 **   in this package.                                                       **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Contributors:                                                          **
 **     RSSOwl - initial API and implementation (bpasero@rssowl.org)         **
 **                                                                          **
 **  **********************************************************************  */

package net.sourceforge.rssowl.controller.thread;

import net.sourceforge.rssowl.controller.DisposeListenerImpl;
import net.sourceforge.rssowl.controller.GUI;
import net.sourceforge.rssowl.dao.ConnectionManager;
import net.sourceforge.rssowl.model.ChannelImage;
import net.sourceforge.rssowl.util.shop.BrowserShop;
import net.sourceforge.rssowl.util.shop.StringShop;

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;

import java.io.IOException;

/**
 * Thread to load an image to a CLabel
 * 
 * @author <a href="mailto:bpasero@rssowl.org">Benjamin Pasero </a>
 * @version 1.2.3
 */
public class ImageLoader extends Thread {

  /** The image to load */
  Image image;

  /** The holder for the image */
  Label imgHolder;

  /** Parent composite */
  Composite parent;

  /** The model for the channel image */
  ChannelImage rssChannelImage;

  /**
   * Instantiate a new ImageLoader Thread
   * 
   * @param rssChannelImage The image informations
   * @param imgHolder CLabel to put the image on
   * @param parent The parent composite
   */
  public ImageLoader(ChannelImage rssChannelImage, Label imgHolder, Composite parent) {
    this.rssChannelImage = rssChannelImage;
    this.imgHolder = imgHolder;
    this.parent = parent;
    setName("Image Loader Thread");
    setDaemon(true);
  }

  /**
   * @see java.lang.Runnable#run()
   */
  public void run() {

    /** Only load Image if a URL is given */
    if (StringShop.isset(rssChannelImage.getImgUrl())) {

      /** Load the image from the URL */
      ConnectionManager connectionManager = new ConnectionManager(rssChannelImage.getImgUrl());
      try {
        connectionManager.setShowLoginDialogIfRequired(false);
        connectionManager.connect();

        /** Create a new image from the InputStream */
        image = new Image(GUI.display, connectionManager.getInputStream());
      } catch (IOException e) {
        GUI.logger.info("ChannelImage()", e);
      }

      /** The Format might not be supported by SWT */
      catch (SWTException e) {
        GUI.logger.info("ChannelImage()", e);
      }

      /** Close connection in any way */
      finally {
        connectionManager.closeConnection();
      }
    }

    /**
     * Place the image on the CLabel if image is not NULL and display still
     * opened
     */
    if (image != null && GUI.isAlive())
      showImage();
  }

  /**
   * Show the image in the imgHolder and configure it to react on Mouseclick to
   * open the link if given.
   */
  private void showImage() {
    GUI.display.asyncExec(new Runnable() {
      public void run() {

        /** Handle situation: imgHolder CLabel disposed */
        if (imgHolder.isDisposed())
          return;

        /** Show image */
        imgHolder.setImage(image);
        imgHolder.addDisposeListener(DisposeListenerImpl.getInstance());

        /** If link is given, set Tooltip and Cursor */
        if (rssChannelImage.getLink() != null) {
          imgHolder.setToolTipText(GUI.i18n.getTranslation("TOOLTIP_URLOPEN"));
          imgHolder.setCursor(GUI.display.getSystemCursor(SWT.CURSOR_HAND));
        }

        /** Open link upon selection */
        imgHolder.addMouseListener(new MouseAdapter() {
          public void mouseDown(MouseEvent e) {

            /** Only handle selection if a link is given */
            if (rssChannelImage.getLink() == null)
              return;

            /** Open link */
            BrowserShop.openLinkInTab(rssChannelImage.getLink());
          }
        });

        /** Update the layout of the parent */
        if (!parent.isDisposed())
          parent.layout();
      }
    });
  }
}