package org.arefgard.container;

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 参照名を保持するクラス。
 * 
 * 「group.target」で構成される文字列を保持する。
 * 
 * @author T.A.K.A.Dark
 *
 */
public class Reference {
	
	private String nameSpace = null;
	private String target = null;
	
	public Reference() {
	}
	
	public Reference(String path) throws IllegalReferenceException {
		try {
			if(path == null || path.equals("")) {
				throw new IllegalReferenceException("パスがありません");
			}
			Pattern pattern = Pattern.compile("^[0-9a-zA-Z]+.[0-9a-zA-Z]+$|^[0-9a-zA-Z]+$");
			Matcher matcher = pattern.matcher(path);
			if(!matcher.find()) {
				throw new IllegalReferenceException("不正なパスです:" + path);
			}
			StringTokenizer tokenizer = new StringTokenizer(path, ".");
			if(tokenizer.countTokens() == 1) {
				this.nameSpace = tokenizer.nextToken();
			}if(tokenizer.countTokens() == 2) {
				this.nameSpace = tokenizer.nextToken();
				this.target = tokenizer.nextToken();
			}
		}catch(Exception e) {
			throw new IllegalReferenceException("実行時例外が発生しました", e);
		}
	}
	
	public String getReferencePath() throws IllegalReferenceException {
		if(this.nameSpace == null || this.nameSpace.equals("")) {
			throw new IllegalReferenceException("パスが不正です");
		}else if(this.target == null || this.target.equals("")) {
			return this.nameSpace;
		}else {
			return nameSpace + "." + target;
		}
	}
	
	public String getNameSpace() {
		return this.nameSpace;
	}
	
	public void setNameSpace(String service) {
		this.nameSpace = service;
	}
	
	public String getTarget() {
		return this.target;
	}
	
	public void setTarget(String bean) {
		this.target = bean;
	}
	
	public String toString() {
		if(this.target != null) {
			return this.nameSpace + "." + this.target;
		}else {
			return this.nameSpace;
		}
	}

}
