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

public class CssTool {
	private static void make( File root ) throws Exception {
		if ( root.isDirectory() ) {
			File[]	list = root.listFiles();
			for ( int i = 0; i < list.length; i++ ) {
				make ( list[i] );
			}
			return;
		}

		String[]	name = root.getName().split( "\\." );
		String[]	path = root.getParent().split( "[/\\\\]" );
		StringBuffer	new_path = new StringBuffer( WRITE_ROOT );
		StringBuffer	pk = new StringBuffer( PACKAGE );
		int	p_no = 0;
		for ( ; p_no < path.length; p_no++ ) {
			if ( READ_ROOT.equals( path[p_no] ) ) {
				p_no++;
				break;
			}
		}
		for ( ; p_no < path.length; p_no++ ) {
			new_path = new_path.append( File.separatorChar );
			new_path = new_path.append( path[p_no] );
			pk = pk.append( "." );
			pk = pk.append( path[p_no] );
			File	new_dir = new File( new_path.toString() );
			new_dir.mkdir();
		}
		new_path = new_path.append( File.separatorChar );
		new_path = new_path.append( name[0] );
		new_path = new_path.append( "_" );
		new_path = new_path.append( name[1] );
		new_path = new_path.append( ".java" );
		pk = pk.append( ";\n" );
		File	new_file = new File( new_path.toString() );

		BufferedReader	br = new BufferedReader(
			new InputStreamReader(
			new FileInputStream( root ) ) );
		BufferedWriter	bw = new BufferedWriter(
			new OutputStreamWriter(
			new FileOutputStream( new_file ) ) );
		SourceHead.init( new File( "../template/head.txt" ) );
		bw.write( SourceHead.getHead() );
		bw.write( pk.toString() );
		bw.write( "public class " );
		bw.write( name[0] );
		bw.write( "_" );
		bw.write( name[1] );
		bw.write( " extends " );
		bw.write( EXTENDS );
		bw.write( " {\n" );
		bw.write( "protected String getFileByte() { return\n" );
		bw.write( "\"" );
		while( true ) {
			String	line = br.readLine();
			if ( line == null )	break;
			char[]	ch = line.toCharArray();
			for ( int i = 0; i < ch.length; i++ ) {
				if ( ch[i] == '"' ) {
					bw.write( "\\\"" );
				}
				else if ( ch[i] == '\t' )	continue;
				else {
					bw.write( ch[i] );
				}
			}
		}
		bw.write( "\";" );
		bw.write( "}\n" );
		bw.write( "public paraselene.HTTPDate getDate() { try{\n" );
		bw.write( "return new paraselene.HTTPDate(\"");
		bw.write( new paraselene.HTTPDate().toString() );
		bw.write( "\");\n}catch(Exception e){}\nreturn null;\n" );
		bw.write( "}\n}\n" );
		bw.close();
		br.close();
	}

	private static final String READ_ROOT = "css";
	private static final String WRITE_ROOT = ".." + File.separator + "paraselene" + File.separator + "mockup" + File.separator + "css";
	private static final String PACKAGE = "package paraselene.mockup.css";
	private static final String EXTENDS = "paraselene.mockup.Output";

	public static void main(String[] a) throws Exception {
		make( new File( ".." + File.separator + READ_ROOT ) );
	}
}

