/*
 * 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.framework.eventdef.xml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.apache.xmlbeans.XmlException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.maskat.ide.MaskatIDEUtil;
import org.maskat.ide.MaskatProjectPropertyPage;
import org.maskat.xml.xmlbeans.InstToXsd;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class TelegramSchemaGenerator {
	/**
	 * イベント定義XMLから、送受信電文のスキーマを生成する（apacheのInst2Xsdツールを使う）
	 * 
	 * @param eventDef
	 * @param project
	 * @param path
	 * @throws CoreException
	 * @throws IOException
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 * @throws TransformerException
	 * @throws XmlException
	 */
	public static void generate(InputStream eventDef, IProject project, IPath path)
			throws CoreException, TransformerException, ParserConfigurationException,
			SAXException, IOException, XmlException {
		NodeList list = EventDefParser.genTeleInstanceFromEventDef(eventDef,
				EventDefParser.EVENTDEF_XSLT_FOR_SCHEMA_GEN);
		if (list != null) {
			for (int i = 0; i < list.getLength(); i++) {
				Node node = list.item(i);
				String componentID = node.getAttributes().getNamedItem("component")
						.getNodeValue();
				String eventID = node.getAttributes().getNamedItem("event")
						.getNodeValue();
				String nodeName = node.getNodeName();
				String fileName = componentID + "_" + eventID + "_" + nodeName + ".xsd";

				Node teleNode = node.getChildNodes().item(0);
				if (teleNode != null) {
					// スキーマファイル保存パス
					ByteArrayOutputStream bo = new ByteArrayOutputStream(512);

					try {

						String targetPath = project
								.getPersistentProperty(MaskatProjectPropertyPage.SCHEMA_FOLDER_PROPERTY);
						if (targetPath == null || "".equals(targetPath.trim())) {
							targetPath = "schema";
							// MessageDialog.openError(PlatformUI.getWorkbench()
							// .getActiveWorkbenchWindow().getShell(), "エラー",
							// "スキーマ生成できませんでした。\n\r"
							// + "プロジェクト属性にスキーマ生成先フォルダを指定してください。");
							// return;
						}
						String folderName = targetPath + "\\" + componentID + "\\"
								+ eventID + "\\" + nodeName + "\\";
						MaskatIDEUtil.createFolder(project, folderName);

						IFile outputFile = project.getFile(folderName + fileName);
						if (!outputFile.exists()) {
							outputFile.create(new ByteArrayInputStream(new byte[0]),
									false, null);
						}

						InstToXsd.transfer(bo, teleNode);
						String xsdStr = bo.toString("UTF-8");// InstToXsd生成したboはUTF-8でエンコードされる
						outputFile.setContents(new ByteArrayInputStream(xsdStr
								.getBytes("UTF-8")), false, false, null);
					} finally {
						bo.close();
					}
				}
			}
		}
	}
}
