/*
 * Copyright 2006 Maskat Project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.maskat.ide.editors;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Collections;
import java.util.Iterator;

import javax.xml.stream.XMLStreamException;

import org.eclipse.core.resources.IFile;
import org.maskat.framework.eventdef.IEventDefSource;
import org.maskat.framework.screendef.LayoutDef;
import org.maskat.framework.screendef.MaskatDef;
import org.maskat.framework.screendef.xml.LayoutDefParser;
import org.maskat.framework.screendef.xml.LayoutDefXmlSerializer;
import org.maskat.ide.editors.linkeventsrc.LinkEventDefSource;
import org.maskat.xml.DefXmlSerializer;

/**
 * The state of layout and event definition. MaskatDef and IEventDefSource's
 * state.
 * 
 * @author shengshen
 * 
 */
public class EditorData {

	EditorData(IFile layoutXmlFile) {
		this.layoutXmlFile = layoutXmlFile;
	}

	protected MaskatDef maskatDef = null;

	/** The index of the layoutDef currently showed */
	protected int layoutIdx = 0;

	IEventDefSource eventDefSource;

	/**	レイアウト定義XML */
	private IFile layoutXmlFile;

	LayoutDef getCurrentLayoutDef() {
		return (LayoutDef) maskatDef.getChildByTypeIdx(LayoutDef.class, this.layoutIdx);
	}

	void switchLayout(int theIdx) {
		layoutIdx = theIdx;
		connectLayoutEvent();
	}

	void connectLayoutEvent() {
		LayoutDef layoutDef = getCurrentLayoutDef();
		layoutDef.setLayoutEvtDefSrc(eventDefSource);
	}

	void loadLayout() throws Exception {
		InputStream inputS = null;
		try {
			if (layoutXmlFile.exists()) {
				inputS = layoutXmlFile.getContents();// contentsからデータを読み込む
				maskatDef = LayoutDefParser.parse(inputS);
			}
		} finally {
			try {
				if (inputS != null)
					inputS.close();
			} catch (IOException e) {
			}
		}
	}

	void loadEvent() throws Exception {
		eventDefSource = new LinkEventDefSource(this.layoutXmlFile);
		eventDefSource.load();
	}

	public Iterator getLayouts() {
		if (maskatDef == null)
			return Collections.EMPTY_LIST.iterator();
		return maskatDef.getTypedChildren(LayoutDef.class);
	}

	void writeLayout(Writer writer) throws XMLStreamException, CloneNotSupportedException {
		DefXmlSerializer serializer = new LayoutDefXmlSerializer((MaskatDef)maskatDef.clone(), writer);
		serializer.write();
	}

	String[] writeEvent() throws Exception {
		return this.eventDefSource.save();
	}
}
