<?php
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'admin.php');

/**
 * All DokuWiki plugins to extend the admin function
 * need to inherit from this class
 */
class admin_plugin_freesync extends DokuWiki_Admin_Plugin {

	var $fshlp = null;

	var $_sync_list_pages = null;
	var $_sync_list_files = null;
	var $_sum = '';
	var $_showSync = 0;
	var $_showDoSync = 0;

	function admin_plugin_freesync () {
		$this->fshlp =& plugin_load('helper', 'freesync');
		if(!$this->fshlp) msg('Loading the freesync helper failed. Make sure that the tags plugin is installed.', -1);
	}

	/**
	 * return some info
	 */
	function getInfo(){
		return array(
        'author' => 'Mikhail I. Izmestev',
        'email'  => 'izmmishao5@gmail.com',
        'date'   => '2009-03-09',
        'name'   => 'freesync dokuwiki plugin',
        'desc'   => 'Free sync plugin',
        'url'    => '',
		);
	}

	/**
	 * return sort order for position in admin menu
	 */
	function getMenuSort() {
		return 999;
	}

	/**
	 * handle user request
	 */
	function handle() {

		$fn   = $_REQUEST['fn'];

		if (is_array($fn)) {
			$cmd = key($fn);
			$param = is_array($fn[$cmd]) ? $fn[$cmd] : null;
		} else {
			$cmd = $fn;
			$param = null;
		}

		$this->fshlp->loadProfile($_REQUEST['profile']);

		switch($cmd) {
			case "save_profile":	$this->fshlp->saveProfile($_REQUEST['oldname'], $param); break;
			case "sync":		$this->_sync(); break;
			case "dosync":		$this->_dosync($_REQUEST['pages'], $_REQUEST['files'], $_REQUEST['sum']); break;
		}

	}

	function _dosync($pages, $files, $summary) {
		$this->_sum = $summary;
		$this->_showDoSync = 1;
		function needmerge($var) {
			return $var != 'nothing';
		}

		if(!is_array($pages))
			$pages = array();
		if(!is_array($files))
			$files = array();
		
		$this->_sync_list_pages = array_filter($pages, "needmerge");
		$this->_sync_list_files = array_filter($files, "needmerge");
	}

	function _sync() {
		$this->_sync_list = $this->fshlp->getPagesDiff();
		if(empty($this->_sync_list))
		msg("All pages are synchronized");
		else
		$this->_showSync = 1;
	}

	function _html_profileSelect() {
		ptln('<div class="half"><fieldset>');
		ptln('<legend>'.$this->getLang('sync_profile').'</legend>');
		ptln('<form method="post">');
		ptln('<select name="profile" class="edit">');
		ptln('<option value="new">'.$this->getLang('new_profile').'</option>');

		$profiles = $this->fshlp->getProfiles();
		reset($profiles);
		while($profile = each($profiles)) {
			ptln('<option value="'.$profile['value'].'"'.
			(($profile['value'] == $this->fshlp->getProfileName())?'selected="selected"':'').
	    '>'.$profile['value'].'</option>');
		}
		ptln('</select>');
		ptln('<input class="button" type="submit" value="'.$this->getLang('select').'"/>');
		ptln('</form>');
		ptln('</fieldset>');

		if($this->fshlp->getProfileName() != "") {
			$this->_html_startSync();
		}

		ptln('</div>');
	}

	function _html_profileEdit() {
		$profile = $this->fshlp->getProfile();
		ptln('<div class="half"><fieldset>');
		ptln('<legend>Edit '.$this->fshlp->getProfileName().' profile</legend>');
		ptln('<table class="inline"><form method="post">');
		ptln('<tr><td><label for="xmlrpcurl">'.$this->getLang('xmlrpcurl').'</label></td>');
		ptln('<td><input type="text" class="edit" name="fn[save_profile][xmlrpcurl]" id="xmlrpcurl" value="'.$profile['xmlrpcurl'].'"/></td></tr>');
		ptln('<tr><td><label for="namespace">'.$this->getLang('namespace').'</label></td>');
		ptln('<td><input type="text" class="edit" name="fn[save_profile][namespace]" id="namespace" value="'.$profile['namespace'].'"/></td></tr>');
		ptln('<tr><td><label for="user">'.$this->getLang('user').'</label></td>');
		ptln('<td><input type="text" class="edit" name="fn[save_profile][user]" id="user" value="'.$profile['user'].'"/></td></tr>');
		ptln('<tr><td><label for="pass">'.$this->getLang('pass').'</label></td>');
		ptln('<td><input type="text" class="edit" name="fn[save_profile][pass]" id="pass" value="'.$profile['pass'].'"/></td></tr>');

		ptln('<tr><td><label for="pages">'.$this->getLang('pages').'</label></td>');
		ptln('<td><input type="checkbox" class="edit" name="fn[save_profile][pages]" id="pages" '.($profile['pages']?'checked="checked"':'').'"/></td></tr>');
		ptln('<tr><td><label for="files">'.$this->getLang('files').'</label></td>');
		ptln('<td><input type="checkbox" class="edit" name="fn[save_profile][files]" id="files" '.($profile['files']?'checked="checked"':'').'"/></td></tr>');
				
		ptln('<tr><td colspan="2"><input type="hidden" name="oldname" value="'.$this->fshlp->getProfileName().'"/>');
		ptln('<input type="submit" class="button" name="fn[save_profile][save]" value="'.$this->getLang('save').'"/></td>');
		ptln('</form>');
		ptln('</table></fieldset></div>');
	}

	function _html_startSync() {
		ptln('<div><fieldset>');
		ptln('<legend>'.$this->getLang('start_sync').'</legend>');
		ptln($this->fshlp->getProfileName().'<br/>');
		ptln('<form method="post">');
		ptln('<input type="hidden" name="profile" value="'.$this->fshlp->getProfileName().'"/>');
		ptln('<input type="submit" name="fn[sync][sync]" class="button" value="'.$this->getLang('sync').'"/>');
		ptln('</form>');
		ptln('</fieldset></div>');
	}

	function _html_showSync() {
		ptln('<div>');
		ptln('<form method="post">');
		ptln('<table class="inline">');
		ptln('<thead>');
		ptln('<tr><th>'.$this->getLang('page').'</th><th>'.$this->getLang('local').'</th><th>&gt;</th><th>=</th><th>&lt;</th><th>'.$this->getLang('remote').'</th><th>'.$this->getLang('diff').'</th></tr>');
		ptln('</thead>');
		ptln('<tbody>');

		while(list($p, $page) = each($this->_sync_list)) {
			ptln('<tr><td>'.$p.'</td>');
			ptln('<td>'.(($page['llastModified'])?date("Y/m/d H:i (", $page['llastModified']).$page['lsize'].' bytes)':'-').'</td>');
			ptln('<td><input class="edit" type="radio" name="'.($page["file"]?'files':'pages').'['.$p.']" value="l2r" '.(($page['llastModified']>$page['rlastModified'])?'checked="checked"':'').'/></td>');
			ptln('<td><input class="edit" type="radio" name="'.($page["file"]?'files':'pages').'['.$p.']" value="nothing"/></td>');
			ptln('<td><input class="edit" type="radio" name="'.($page["file"]?'files':'pages').'['.$p.']" value="r2l" '.(($page['llastModified']<$page['rlastModified'])?'checked="checked"':'').'/></td>');
			ptln('<td>'.(($page['rlastModified'])?date("Y/m/d H:i (", $page['rlastModified']).$page['rsize'].' bytes)':'-').'</td>');
			ptln('<td>'.((!$page["file"] && $page['llastModified'] && $page['rlastModified'])?'<a href="javascript:plugin_freesync_diff(\''.$p.'\', \''.$this->fshlp->getProfileName().'\')">Diff</a>':'').'</td>');
			ptln('</tr>');
		}
		ptln('</tbody>');
		ptln('</table>');
		ptln('<input type="hidden" name="profile" value="'.$this->fshlp->getProfileName().'"/>');
		ptln('<label>'.$this->getLang('sum').'<input class="edit" name="sum" type="text"/></label>');
		ptln('<input type="submit" class="button" name="fn[dosync]" value="'.$this->getLang('dosync').'"/>');
		ptln('</form>');
		ptln('</div>');
	}

	function _html_doSync() {
		ptln('<ul>');
		if(!empty($this->_sync_list_pages)) {
			foreach($this->_sync_list_pages as $page => $direction) {
				ptln('<li>');
				ptln($this->getLang('pull').' '.$page.'...');
				ptln('<span id="'.$page.'">');
				ptln('<script type="text/javascript" language="javascript">');
				ptln('_sync_queue.push(Array("'.$page.'", "call=_freesync_page_'.$direction.'&profile='.$this->fshlp->getProfileName().'&id='.$page.'&sum='.$this->_sum.'"));');
				ptln('</script>');
				ptln('</span>');
				ptln('</li>');
			}
		}
		if(!empty($this->_sync_list_files)) {
			foreach($this->_sync_list_files as $file => $direction) {
				ptln('<li>');
				ptln($this->getLang('pull').' '.$file.'...');
				ptln('<span id="'.$file.'">');
				ptln('<script type="text/javascript" language="javascript">');
				ptln('_sync_queue.push(Array("'.$file.'", "call=_freesync_file_'.$direction.'&profile='.$this->fshlp->getProfileName().'&id='.$file.'&sum='.$this->_sum.'"));');
				ptln('</script>');
				ptln('</span>');
				ptln('</li>');
			}
		}
		ptln('</ul>');
		ptln('<script type="text/javascript" language="javascript">');
		ptln("addEvent(window,'load', plugin_freesync_sync);");
		ptln('</script>');
	
	}

	/**
	 * output appropriate html
	 */
	function html() {
		print $this->locale_xhtml('intro');

		ptln('<div id="free__sync">');

		if($this->_showSync) {
			$this->_html_showSync();
		}elseif($this->_showDoSync) {
			$this->_html_doSync();
		}else {
			$this->_html_profileSelect();
			$this->_html_profileEdit();
		}

		ptln('</div>');
	}

}
