/*
 * Copyright, 2009 Koichi Takahashi. All Rights Reserved.
 * 
 * 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 com.nec.exi.editor.wizards;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Properties;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

import com.siemens.ct.exi.EXIEncoder;
import com.siemens.ct.exi.EXIFactory;
import com.siemens.ct.exi.GrammarFactory;
import com.siemens.ct.exi.helpers.DefaultEXIFactory;

/**
 * @author Koichi Takahashi
 */
public class NewFileWizard extends Wizard implements INewWizard {
	private NewFilePage page1;
	private OptionSettingPage page2;
	private IStructuredSelection selection;
	private EXIFactory factory = null;
	private GrammarFactory gFactory = null;

	public NewFileWizard() {
		super();
		setNeedsProgressMonitor(true);
		factory = DefaultEXIFactory.newInstance();
		gFactory = GrammarFactory.newInstance();
	}
	
	public void addPages() {
		page1 = new NewFilePage(selection);
		page2 = new OptionSettingPage(selection);
		addPage(page1);
		addPage(page2);
	}
	
	public boolean performFinish() {
		IFile iFile = page1.createNewFile();
		if(null == iFile){
			return false;
		}
		
		File ioFile = iFile.getRawLocation().toFile();
		File parent = ioFile.getParentFile();
		File propertyFile = new File(parent.getAbsolutePath() + File.separator + ".schema");
		String _fileName = ioFile.getName();
		_fileName = _fileName.substring(0, _fileName.length()-4);
		File xsdFile = new File(parent.getAbsolutePath() + File.separator + _fileName + ".xsd");
		Properties property = new Properties();
		
		// .schema
		try {
			for(String propertyFileName : parent.list()){
				if(".schema".equals(propertyFileName)){
					property.loadFromXML(new FileInputStream(propertyFile));					
					break;
				}
			}
			if(page2.isSchemaRef()){
				property.setProperty(iFile.getName(), xsdFile.getAbsolutePath());
			}else{
				property.remove(iFile.getName());
			}
			property.storeToXML(new FileOutputStream(propertyFile), null);
		} catch(Exception e){
			return false;
		}
		
		// tmp.xsd
		if(page2.isSchemaRef()){
			if(!writeSchemaFile(parent, _fileName)){
				return false;
			}			
		}
		
		// tmp.exi
		FileOutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(ioFile);
			factory.setCodingMode(page2.getCodingMode());
			if(page2.isSchemaRef()){
				factory.setGrammar(gFactory.createGrammar(xsdFile.toURI().toString()));
			}
			EXIEncoder encoder = factory.createEXIEncoder();
			encoder.setOutput(outputStream, false);
			encoder.encodeStartDocument();
			encoder.encodeStartElement("", "tmp", null);
			encoder.encodeEndElement();
			encoder.encodeEndDocument();
		} catch (Exception e) {
			return false;
		} finally {
			if(null != outputStream){
				try {
					outputStream.close();
				} catch (IOException e) {
					return false;
				}
			}
		}

		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		try {
			iFile.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
			IDE.openEditor(page, iFile, true);
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}

	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
	
	private boolean writeSchemaFile(File dir, String _fileName) {
		FileOutputStream xsd = null;
		OutputStreamWriter xsdWriter = null;
		PrintWriter writer = null;
		try{
			xsd = new FileOutputStream(dir.getAbsolutePath() + File.separator + _fileName + ".xsd");
			xsdWriter = new OutputStreamWriter(xsd, "UTF-8");
			writer = new PrintWriter(xsdWriter);
			writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			writer.println("<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
			writer.println("  <xsd:element name=\"tmp\"/>");
			writer.println("</xsd:schema>");
		}catch(Exception e){
			return false;
		}finally{
			if(null != writer){
				writer.close();
			}
			try {
				if(null != xsdWriter){
					xsdWriter.close();
				}
				if(null != xsd){
					xsd.close();
				}
			} catch (IOException e) {
				return false;
			}
		}
		return true;
	}
}