/*
 * D2F
 * Copyright (C) SatisKia. All rights reserved.
 */

#include "_Global.h"

class _SharedObject
{
	var _m:_Main;

	var _so:SharedObject;

	var _start:Number;
	var _str:String;

	function _SharedObject( m:_Main, name:String )
	{
		_m = m;

		_so = SharedObject.getLocal( name );

		_str = new String( "" );
	}

	function getParameter( key:String ):String
	{
		return _m.readParameter( _so.data.str, key );
	}

	function setParameter( key:String, str:String ):Void
	{
		if( _so.data.str == undefined )
		{
			_so.data.str = key + "=" + escape( str );
			return;
		}
		var forward:String = new String( "" );
		var backward:String = new String( "" );
		var start:Number = _so.data.str.indexOf( key + "=", 0 );
		if( start >= 0 )
		{
			if( start > 0 )
			{
				forward = _so.data.str.substring( 0, start );
			}
			start += key.length + 1;
			var end:Number = _so.data.str.indexOf( "&", start );
			if( end >= 0 )
			{
				backward = _so.data.str.substring( end, _so.data.str.length );
			}
			_so.data.str = forward + key + "=" + escape( str ) + backward;
		}
		else
		{
			_so.data.str += "&";
			_so.data.str += key;
			_so.data.str += "=";
			_so.data.str += escape( str );
		}
	}

	function beginRead():Void
	{
		_start = 0;
	}
	function read():String
	{
		if( _start >= _so.data.str.length )
		{
			_str = "";
		}
		else
		{
			var end:Number = _so.data.str.indexOf( "&", _start );
			if( end < 0 ) end = _so.data.str.length;
			_str = _so.data.str.substring( _start, end );
			_start = end + 1;
		}
		return unescape( _str );
	}
	function endRead():Void
	{
		_str = "";
	}

	function beginWrite():Void
	{
		_str = "";
	}
	function write( str:String ):Void
	{
		if( _str.length > 0 )
		{
			_str += "&";
		}
		_str += escape( str );
	}
	function endWrite():Void
	{
		_so.data.str = _str;
		_so.flush();
		_str = "";
	}
}
