/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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 woolpack.locale;

import java.io.IOException;
import java.util.Locale;

import woolpack.dom.DomContext;
import woolpack.dom.DomExpression;

/**
 * スレッドの{@link Locale}を元に id に接尾子を付加し、DOM ノードの生成を委譲する{@link DomExpression}。
 * @author nakamura
 *
 */
public class LocaleId implements DomExpression {
	private final DomExpression nodeMaker;
	private final ThreadLocal<Locale> threadLocal;
	
	/**
	 * コンストラクタ。
	 * @param nodeMaker DOM ノードを生成し加工する委譲先。ステートレスであるべき。
	 * @param threadLocal 現在のスレッドの{@link Locale}を保持する{@link ThreadLocal}。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 */
	public LocaleId(final DomExpression nodeMaker, final ThreadLocal<Locale> threadLocal){
		nodeMaker.getClass();
		threadLocal.getClass();
		this.nodeMaker = nodeMaker;
		this.threadLocal = threadLocal;
	}

	public void interpret(final DomContext context) {
		final String id = context.getId();
		final Locale l = threadLocal.get();

		final Locale d = Locale.getDefault();
		final String[] idArray;
		if(l == null){
			idArray = new String[]{
					id + "_" + d.getLanguage() + "_" + d.getCountry() + "_" + d.getVariant(),
					id + "_" + d.getLanguage() + "_" + d.getCountry(),
					id + "_" + d.getLanguage(),
					id
			};
		}else{
			idArray = new String[]{
					id + "_" + l.getLanguage() + "_" + l.getCountry() + "_" + l.getVariant(),
					id + "_" + l.getLanguage() + "_" + l.getCountry(),
					id + "_" + l.getLanguage(),
					id + "_" + d.getLanguage() + "_" + d.getCountry() + "_" + d.getVariant(),
					id + "_" + d.getLanguage() + "_" + d.getCountry(),
					id + "_" + d.getLanguage(),
					id
			};
		}
		try{
			RuntimeException e0 = null;
			for(int i=0; i<idArray.length; i++){
				try{
					context.setId(idArray[i]);
					nodeMaker.interpret(context);
					if(context.getNode() != null){
						break;
					}
				}catch(final RuntimeException e){
					if(e.getCause() instanceof IOException){
						e0 = e;
					}else{
						throw e;
					}
				}
			}
			if(context.getNode() == null){
				if(e0 != null){
					throw e0;
				}else{
					throw new RuntimeException();
				}
			}
		}finally{
			context.setId(id);
		}
	}
}
