/*
 * Paraselene
 * Copyright (c) 2009, 2010  Akira Terasaki
 * このファイルは同梱されているLicense.txtに定めた条件に同意できる場合にのみ
 * 利用可能です。
 */
package paraselene.ajax.data;

import paraselene.*;
import paraselene.supervisor.*;
import paraselene.tag.*;
import paraselene.ui.*;
import java.io.*;
import java.util.*;

public class TagData implements Serializable {
	private static final long serialVersionUID = 2L;

	public String	id = "";
	public String	body = "";
	public String[]	cmd = null;
	public boolean	over_f = false;

	TagData(){}
	TagData( Tag tag ) {
		this( tag, true );
	}

	private void init( Tag tag ) {
		Page	page = tag.getAssignedPage();
		if ( SandBox.isCurrentDaemon() ) {
			PageHooker[]	org = page.getPageHooker();
			PageHooker[]	hook = tag.getInnerHTMLPart( org );
			for ( int i = 0; i < hook.length; i++ ) {
				hook[i].commitDaemon();
			}
			for ( int i = 0; i < org.length; i++ ) {
				if ( org[i] instanceof PageBypassedDiv ) {
					org[i].commitDaemon();
				}
			}
		}
		int cnt = tag.getHTMLPartCount();
		JsonWriter	w = new JsonWriter();
		for ( int i = 0; i < cnt; i++ ) {
			tag.getHTMLPart( i ).write( w, HTMLPart.StringMode.BODY );
		}
		body = w.toString();
		page = page.getParentPage();
		cmd = new String[]{ page.getOnLoadScript() };
		page.resetOnLoadScript();
		tag.resetModify();
	}

	TagData( Tag tag, boolean flag ) {
		this.id = tag.getAttributeToString( "id" );
		if ( tag instanceof PageBypassedDiv ) {
			tag.resetModify();
			PageBypassedDiv	div = (PageBypassedDiv)tag;
			Page	page = div.getViewPage();
			if ( page == null )	return;
			tag = page.getBodyTag();
			if ( tag == null )	return;
		}
		if ( flag ) {
			init( tag );
		}
	}


	public static TagData[] getTag( Page org, Page out ) {
		ArrayList<TagData>	list = new ArrayList<TagData>();
		if ( org == out ) {
			Tag[]	tag = out.getModifiedTag();
			for ( int i = 0; i < tag.length; i++ ) {
				list.add( new TagData( tag[i] ) );
			}
			int	cnt = list.size();
			if ( cnt > 1 ) {
				list.get( cnt - 1 ).cmd = list.get( 0 ).cmd;
				list.get( 0 ).cmd = null;
			}
		}
		else {
			TagData	td = new TagData( out.getBodyTag() );
			td.id = org.getRootID();
			list.add( td );
		}
		return list.toArray( new TagData[0] );
	}
}

