<?php /* -*- Mode: php; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */

global $UTIL_DIR, $MODULES_DIR;

include_once($UTIL_DIR . "/rss.php");
include_once($UTIL_DIR . "/convert.php");
include_once($UTIL_DIR . "/forms.php");
include_once($UTIL_DIR . "/user.php");
include_once($MODULES_DIR . "/icons.php");
include_once($UTIL_DIR . "/markdown.php");

class NewsEntry {
  public $title;
  public $time;
  public $description;
  public $category;
	public $userid;
	public $icon;

  public function show()
  {
		global $users, $DATA_DIR, $ICONS_DIR, $NEWS_PAGE;

		if(!isset($users)) $users = new Users($DATA_DIR . "/users.xml");

    $content = Markdown(htmlspecialchars_decode($this->description));

		$icons = new Icons($ICONS_DIR."/");
		$icon = $icons->icons[$this->icon];

		$userid = $users->findUser($this->userid)->userid;
		if(!$userid) $userid = "admin"; // Fallback from old data.

    $str = "<div class=\"news_entry\">\n";
    $str .= "  <div class=\"news_time\">" .
			date("D M jS Y G:i", $this->time) . "</div>\n";
    $str .= "  <div class=\"news_title\">\n";
		$str .= "    <a href=\"?page=".$NEWS_PAGE."&amp;newsid=".$this->time."\">" .
      htmlspecialchars_decode($this->title, ENT_QUOTES) . "</a>\n";
		$str .= "  </div>\n";
		$str .= "  <div class=\"news_user\">By: " . $userid . "</div>\n";
		$str .= "  <div class=\"news_description\">\n";
		if($this->icon) $str .= "    <img alt=\"icon\" class=\"news_icon\" src=\"" .
											$icon->prefix.$icon->file . "\"/>\n";
		$str .= "    ".$content. "\n";
		$str .= "  </div>\n";
    $str .= "</div>\n";
    return $str;
  }

	public function write($fp)
	{
		fwrite($fp, "  <newsentry title=\"".xmlenc($this->title)."\"\n");
		fwrite($fp, "             time=\"" . xmlenc($this->time) . "\"\n");
		fwrite($fp, "             category=\"" . xmlenc($this->category) . "\"\n");
		fwrite($fp, "             userid=\"" . xmlenc($this->userid) . "\"\n");
    fwrite($fp, "             icon=\"" . xmlenc($this->icon) . "\">");
		fwrite($fp, xmlenc($this->description));
		fwrite($fp, "</newsentry>\n");
	}

	public function __toString()
	{
		return $this->title;
	}

  public function NewsEntry($title, $time, $category,
														$description, $userid, $icon)
  {
    $this->title = $title;
    $this->time = $time;
    $this->category = $category;
    $this->description = $description;
		$this->userid = $userid;
		$this->icon = $icon;
  }
}

class News {

  private $file;
  private $news = array();

  // Admin config
  public $admin_title = "News";
  public $admin_submodules = array("New entry" => "new",
																	 "Edit entry" => "edit",
																	 "Delete entry" => "delete");
	
  public function admin_add($action, $vars)
	{
		global $UID, $ICONS_DIR;

		switch($action) {
		case "add":
			$n = new NewsEntry($vars["title"],
												 DateTimeEdit::toTimestamp($vars, "time"),
												 $vars["category"], $vars["description"],
												 $UID, $vars["icon"]);
			echo "\"" .$n->title . "\" has now been added.";
			$this->add($n);
			$this->write();
			break;
			
		case "preview":
			$n = new NewsEntry($vars["title"],
												 DateTimeEdit::toTimestamp($vars, "time"),
												 $vars["category"], $vars["description"],
												 $UID, $vars["icon"]);
			echo "<div class=\"preview\">\n";
			echo "<div class=\"content\">\n";
			echo $n->show();
			echo "</div>\n";
			echo "</div>\n";
			echo "<p>Looking ok?</p>";
			$form = new Form("add");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new Button("yes"));
			$form->render();

			$form = new Form("retry");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new Button("no"));
			$form->render();
			break;
			
		case "retry":
			$title = $vars["title"];
			$time = DateTimeEdit::toTimestamp($vars, "time");
			$category = $vars["category"];
			$description = $vars["description"];
      $icon = $vars["icon"];
		default:
			$form = new Form("preview");
			$form->addWidget(new LineEdit("Title", "title", $title));
			$form->addWidget(new DateTimeEdit("Time", "time", $time));
			$form->addWidget(new ComboBox("Category", "category", $category,
																		array("Main" => "main", "Site" => "site")));
			$form->addWidget(new TextEdit("Description", "description", $description));
			$form->addWidget(new ImageComboBox("Icon", "icon", $icon,
																				 new Icons($ICONS_DIR."/")));
			$form->addWidget(new Button("Post news"));
			$form->render();
			break;
		}
	}

	public function admin_edit($action, $vars)
	{
		global $UID, $ICONS_DIR;

		switch($action) {
		case "add":
			$this->news[$vars["newsid"]]->title = $vars["title"];
			$this->news[$vars["newsid"]]->userid = $UID;
			$this->news[$vars["newsid"]]->time = DateTimeEdit::toTimestamp($vars, "time");
			$this->news[$vars["newsid"]]->category = $vars["category"];
			$this->news[$vars["newsid"]]->description = $vars["description"];
			$this->news[$vars["newsid"]]->icon = $vars["icon"];
			$this->write();
			echo "\"" . $this->news[$vars["newsid"]]->title . "\" has now been edited.";
			break;
			
		case "preview":
			$n = new NewsEntry($vars["title"], DatetimeEdit::toTimestamp($vars, "time"),
												 $vars["category"], $vars["description"], $UID, $vars["icon"]);
			echo "<div class=\"preview\">\n";
			echo "<div class=\"content\">\n";
			echo $n->show();
			echo "</div>\n";
			echo "</div>\n";
			echo "<p>Looking ok?</p>";
			$form = new Form("add");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new Button("yes"));
			$form->render();

			$form = new Form("retry");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new Button("no"));
			$form->render();
			break;
			
		case "edit":
		case "retry":
			if(isset($vars["title"])) $title = $vars["title"];
			else $title = $this->news[$vars["newsid"]]->title;
			if(isset($vars["time_year"])) $time = DateTimeEdit::toTimestamp($vars, "time");
			else $time = $this->news[$vars["newsid"]]->time;
			if(isset($vars["category"])) $category = $vars["category"];
			else $category = $this->news[$vars["newsid"]]->category;
			if(isset($vars["description"])) $description = $vars["description"];
			else $description = $this->news[$vars["newsid"]]->description;
			if(isset($vars["icon"])) $icon = $vars["icon"];
			else $icon = $this->news[$vars["newsid"]]->icon;
			
			$form = new Form("preview");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new LineEdit("Title", "title", $title));
			$form->addWidget(new DateTimeEdit("Time", "time", $time));
			$form->addWidget(new ComboBox("Category", "category", $category,
																		array("Main" => "main", "Site" => "site")));
			$form->addWidget(new TextEdit("Description", "description", $description));
			$form->addWidget(new ImageComboBox("Icon", "icon", $icon, new Icons($ICONS_DIR."/")));
			$form->addWidget(new Button("Post news"));
			$form->render();
			break;
			
		case "select":
		default:
			$newslist = array();
			foreach($this->news as $newsentry) {
				$newslist[date("Y-m/d h:i:s", $newsentry->time) . ": " .
                  $newsentry->title] = $newsentry->time; 
			}
      krsort($newslist);

			$form = new Form("edit");
			$form->addWidget(new ComboBox("Edit this entry:", "newsid", "", $newslist));
			$form->addWidget(new Button("Edit..."));
			$form->render();
			break;
		}
	}

  public function admin_delete($action, $vars)
	{
		switch($action) {
		case "delete":
			echo "\"". $this->news[$vars["newsid"]]->title . "\" has now been deleted.";
			unset($this->news[$vars["newsid"]]);
			$this->write();
			break;
			
		case "confirm":
			echo "Really delete: " . $this->news[$vars["newsid"]]->title . "?";
			$form = new Form("delete");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new Button("yes"));
			$form->render();

			$form = new Form("select");
			$form->addWidget(new Hidden($vars));
			$form->addWidget(new Button("no"));
			$form->render();
			break;
			
		case "select":
		default:
			$newslist = array();
			foreach($this->news as $newsentry) {
				$newslist[date("Y-m/d h:i:s", $newsentry->time) . ": " .
                  $newsentry->title] = $newsentry->time; 
			}
      krsort($newslist);

			$form = new Form("confirm");
			$form->addWidget(new ComboBox("Delete this entry:", "newsid", "", $newslist));
			$form->addWidget(new Button("Delete..."));
			$form->render();
			break;
		}
	}

  public function admin($sub, $action, $vars)
  {
    switch($sub) {
    case "new":
			$this->admin_add($action, $vars);
      break;

    case "edit":
			$this->admin_edit($action, $vars);
      break;

    case "delete":
			$this->admin_delete($action, $vars);
      break;
    }
  }

  public function run($params)
  {
		global $newsid;

		$str = "";

		$module = "all";
		$number = -1;
		$single = false;

		foreach($params as $param => $value) {
			switch($param) {
			case "show":
				$module = $value;
				break;

			case "number":
				$number = $value;
				break;

			case "single":
				$single = true;
				break;
			}
		}
		
		if($single) {
			if($newsid && $this->news[$newsid]) {
				//			$str .= $this->show($number, $module);
				$str .= $this->news[$newsid]->show();
			} else {
				$str .= "<strong>No such news entry!</strong>\n";
			}
		} else {
			$str .= $this->show($number, $module);
		}

		return $str;
  }

  public function show($number, $category)
  {
    $str = "";

    // If number is -1 show all shows.
    if($number == -1) $number = 100000;

    foreach($this->news as $newsentry) {
      if($newsentry->category == $category || $category == "all") {
				$str .= $newsentry->show();
				$number--;
      }
      if(!$number) return $str;
    }
    return $str;
  }

  public function add($newsentry) {
    $key = $newsentry->time;
    $this->news[$key] = $newsentry;
  }
	
  public function write()
  {
    $fp = fopen($this->file, "w");
    fwrite($fp, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

    fwrite($fp, "<news>\n");
    foreach($this->news as $newsentry) {
			$newsentry->write($fp);
    }
    fwrite($fp, "</news>\n");

    fclose($fp);

		$rss = new RSS($this->file, "rss.xml");
		$rss->write();
  }
	
  private function read()
  {
    $dom = new DomDocument;
    $dom->preserveWhiteSpace = FALSE;
    $dom->load($this->file);
    $params = $dom->getElementsByTagName('newsentry');

    foreach ($params as $param) {
      $newsentry = new NewsEntry($param->getAttribute('title'),
																 $param->getAttribute('time'),
																 $param->getAttribute('category'),
																 $param->textContent,
																 $param->getAttribute('userid'),
																 $param->getAttribute('icon'));
      $this->add($newsentry);
    }
		
    // Key sort
    krsort($this->news);
  }

  public function News($file)
  {
    $this->file =  $file;
    if(file_exists($file)) $this->read();
  }

}

function news_init()
{
  global $DATA_DIR;
  return new News($DATA_DIR . "/news.xml");
}
?>