/*   **********************************************************************  **
 **   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.util.shop;

import net.sourceforge.rssowl.controller.GUI;
import net.sourceforge.rssowl.controller.MessageBoxFactory;
import net.sourceforge.rssowl.controller.dialog.PreferencesDialog;
import net.sourceforge.rssowl.controller.thread.StreamGobbler;
import net.sourceforge.rssowl.model.Category;
import net.sourceforge.rssowl.model.NewsItem;
import net.sourceforge.rssowl.util.GlobalSettings;

import org.eclipse.swt.SWT;
import org.jdom.Text;

import java.io.IOException;

/**
 * Factory class for blogging concerns in RSSOwl
 * 
 * @author <a href="mailto:bpasero@rssowl.org">Benjamin Pasero </a>
 * @version 1.2.3
 */
public class BlogShop {

  /** The blogger executable and arguments */
  static String executable;

  /** This utility class constructor is hidden */
  private BlogShop() {
  // Protect default constructor
  }

  /**
   * Blog a newsitem. This method first checks if a blogger is set and then
   * executes it with the given arguments. If the user has used wildcards, they
   * are added to the arguments.
   * 
   * @param rssNewsItem The Newsitem to blog
   */
  public static void blogNews(NewsItem rssNewsItem) {

    /** Check if a blogger is set */
    if (!isBloggerSet())
      return;

    /** Link of Newsitem */
    String newslink = rssNewsItem.getLink();

    if (newslink == null && rssNewsItem.getGuid() != null)
      newslink = rssNewsItem.getGuid();
    else if (newslink == null)
      newslink = "";

    /** Link of Newsfeed */
    String feedlink = rssNewsItem.getNewsfeedXmlUrl();

    if (feedlink == null)
      feedlink = "";

    /** If this is a aggregated category, use the feed title to get the XML Url */
    if (rssNewsItem.isPartOfAggregation())
      feedlink = rssNewsItem.getNewsfeedTitle();

    /** The URL could be the title of a favorite */
    if (Category.getLinkForTitle(feedlink) != null)
      feedlink = Category.getLinkForTitle(feedlink);

    /** Title of Newsitem */
    String title = rssNewsItem.getTitle();

    if (!StringShop.isset(title))
      title = GUI.i18n.getTranslation("NO_TITLE");

    /** Build arguments to blogger */
    String args = GlobalSettings.bloggerArguments;

    /** Newslink */
    args = StringShop.replaceAll(args, "[NEWSLINK]", newslink);

    /** Feedlink */
    args = StringShop.replaceAll(args, "[FEEDLINK]", feedlink);

    /** Title - Replace Quotes with single quotes */
    args = StringShop.replaceAll(args, "[TITLE]", StringShop.replaceAll(title, "\"", "'"));

    /** Author */
    if (StringShop.isset(rssNewsItem.getAuthor()))
      args = StringShop.replaceAll(args, "[AUTHOR]", rssNewsItem.getAuthor());

    /** Category */
    if (StringShop.isset(rssNewsItem.getCategory()))
      args = StringShop.replaceAll(args, "[CATEGORY]", rssNewsItem.getCategory());

    /** Description - Replace Quotes with single quotes */
    if (StringShop.isset(rssNewsItem.getDescription()))
      args = StringShop.replaceAll(args, "[DESCRIPTION]", StringShop.replaceAll(rssNewsItem.getDescription(), "\"", "'"));
    else
      args = StringShop.replaceAll(args, "[DESCRIPTION]", GUI.i18n.getTranslation("NEWS_NO_DESCRIPTION"));

    /** Publish Date */
    if (StringShop.isset(rssNewsItem.getPubDate()))
      args = StringShop.replaceAll(args, "[PUBDATE]", rssNewsItem.getPubDate());

    /** Publisher */
    if (StringShop.isset(rssNewsItem.getPublisher()))
      args = StringShop.replaceAll(args, "[PUBLISHER]", rssNewsItem.getPublisher());

    /** Source */
    if (StringShop.isset(rssNewsItem.getSource()))
      args = StringShop.replaceAll(args, "[SOURCE]", rssNewsItem.getSource());

    /** Normalize args */
    args = Text.normalizeString(args);

    /** Build executable with arguments */
    executable = GlobalSettings.bloggerPath + " " + args;

    /** Launch blogger in seperate thread */
    Thread launcher = new Thread("Blogger Launcher") {

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

        /** Execute blogger */
        try {
          Process proc = Runtime.getRuntime().exec(executable);

          /** Let StreamGobbler handle error message */
          StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());

          /** Let StreamGobbler handle output */
          StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream());

          /** Flush both error and output streams */
          errorGobbler.start();
          outputGobbler.start();

          /** Wait for the process to terminate */
          proc.waitFor();
        }

        /** Log any error */
        catch (IOException e) {
          GUI.logger.log("blogNews", e);
        }

        /** Log any error */
        catch (InterruptedException e) {
          GUI.logger.log("blogNews", e);
        }
      }
    };
    launcher.setDaemon(true);
    launcher.start();
  }

  /**
   * Check if a blogger is set and give out warning if it is not set.
   * 
   * @return boolean TRUE if the blogger is set
   */
  private static boolean isBloggerSet() {

    /** Give out warning if blogger is not set */
    if (GlobalSettings.bloggerPath.equals("")) {
      MessageBoxFactory.showMessage(GUI.shell, SWT.ICON_WARNING, GUI.i18n.getTranslation("POP_BLOG_NEWS"), GUI.i18n.getTranslation("DIALOG_BLOGGER_ATTENTION"));

      /** Prompt for the blogger */
      PreferencesDialog.lastOpenedPropertyPage = 8;
      new PreferencesDialog(GUI.shell, GUI.i18n.getTranslation("MENU_PREFERENCES"), GUI.rssOwlGui).open();

      /** Return blogger not set */
      return false;
    }
    return true;
  }
}