<?php
class TCommandAnalyzer {
	var $src;
	var $dist;
	var $commands = array();
	function __construct($src='') {
		$this->dist = $this->src = $src;
	}

	function clear($src='') {
		$this->dist = $this->src = $src;
	}

	function analysis() {
		$src_len = mb_strlen($this->src);
		$i = 0;

		$commands = array();
		$commands['themetag'] = '#[\S]+';
		$commands['url']      = 'https?://\S+';
		$commands['reply']    = '>>[0-9]+';
		//$commands['mention']  = '@[0-9a-zA-Z_]+';

		$matches = array();
		$ret = preg_match_all('('.implode('|', $commands).')', $this->src, $matches, PREG_OFFSET_CAPTURE);
		if (! $ret) {
			$this->dist = $this->src;
			return;
		}

		$this->commands = array();

		foreach ($matches as $m1) {
			foreach ($m1 as $m) {
				$c = substr($m[0], 0, 1);
				if ($c == '#') {
					$this->commands[] = new ThemeCommand($m[1], substr($m[0],1));
				} else if ($c == '>') {
					$this->commands[] = new ReplyCommand($m[1], (int)substr($m[0], 2));
				//} else if ($c == '@') {
				//	$this->commands[] = new MentionCommand($m[1], substr($m[0],1));
				} else {
					$this->commands[] = new UrlCommand($m[1], $m[0]);
				}
			}
		}
		return TRUE;
	}

	function deleteDist($cmds) {
		$ret = '';
		$i = 0;
		if (empty($cmds)) {
			$ret = $this->src;
		} else {
			foreach ($cmds as $cmd) {
				$cmd->offset;
				$len = strlen($cmd->getFull());
				$ret .= substr($this->src, $i, $cmd->offset - $i);
				$i = $cmd->offset + $len;
			}
			$ret .= substr($this->src, $i);
		}
		$this->dist = $ret;
	}
}
class TCommand {
	var $target;
	var $offset;
	function __construct($offset, $target) {
		$this->offset = $offset;
		$this->target = $target;
	}
	function getFull() {
		return $this->target;
	}
}
class ThemeCommand extends TCommand {
	function getFull() {
		return '#'.$this->target;
	}
}
class MentionCommand extends TCommand {
	function getFull() {
		return '@'.$this->target;
	}
}
class UrlCommand extends TCommand {
	function getFull() {
		return $this->target;
	}
}
class ReplyCommand extends TCommand {
	function getFull() {
		return '>>'.$this->target;
	}
}
