/*
 * 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.dom;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.w3c.dom.Node;

/**
 * 同一セッションで同一の id のリクエストが既に実行中の場合、
 * 委譲先を実行せずに先に実行されている処理が終了するのを待ち
 * 実行結果の DOM ノードを再利用する{@link DomExpression}。
 * 適用しているパターン：Proxy、Before After、Bolking。
 * @author nakamura
 *
 */
public class JoinProcess implements DomExpression {
	/**
	 * id と内部クラスの{@link ConcurrentMap}を格納する{@link DomContext#getSession()}のキーのデフォルト値。
	 */
	public static final String KEY = "woolpack.dom.JOIN_PROCESS";
	
	private final DomExpression expression;
	private final String key;
	
	/**
	 * コンストラクタ。
	 * @param key id と内部クラスの{@link ConcurrentMap}を格納する{@link DomContext#getSession()}のキー。
	 * @param expression 委譲先。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 * @throws StringIndexOutOfBoundsException key が空の場合。
	 */
	public JoinProcess(final String key, final DomExpression expression){
		key.charAt(0);
		expression.getClass();
		
		this.key = key;
		this.expression = expression;
	}

	/**
	 * コンストラクタ。
	 * @param expression 委譲先。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 * @throws StringIndexOutOfBoundsException key が空の場合。
	 */
	public JoinProcess(final DomExpression expression){
		this(KEY, expression);
	}
	
	private Process createPerSession(final ConcurrentMap<String,Object> session, final String id){
		ConcurrentMap<String,Process> map = null;
		while(true){
			map = (ConcurrentMap<String,Process>)session.get(key);
			if(map != null){
				break;
			}
			session.putIfAbsent(key, new ConcurrentHashMap<String,Process>());
		}
		while(true){
			final Process process = map.get(id);
			if(process != null){
				return process;
			}
			map.putIfAbsent(id, new Process());
		}
	}

	/**
	 * @throws NullPointerException 引数または{@link DomContext#getId()}または{@link DomContext#getSession()}が null の場合。
	 */
	public void interpret(final DomContext context) {
		final Process process = createPerSession(context.getSession(), context.getId());
		if(process.isNew()){
			expression.interpret(context);
			process.setNode(context.getNode());
		}else{
			context.setNode(process.getNode());
		}
	}
	
	class Process{
		private int count;
		private Node node;
		
		synchronized boolean isNew(){
			count++;
			return (count == 1);
		}
		
		synchronized void setNode(final Node node){
			count--;
			if(count >= 1){
				this.node = node;
			}
			this.notifyAll();
		}
		
		synchronized Node getNode(){
			try{
				while(node == null){
					try {
						this.wait();
					} catch (final InterruptedException e) {
						Thread.currentThread().interrupt();
						throw new RuntimeException(e);
					}
				}
				return this.node;
			}finally{
				count--;
				if(count == 0){
					this.node = null;
				}
			}
		}
	}
}
