package com.ftinc.si.assist.test;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

public class JSONRecord extends Record {
	private static HashMap<String, JSONRecord> s_map = new HashMap<String, JSONRecord>();
	
	public JSONRecord() {
		super(0);
	}

	public JSONRecord(int i) {
		super(i);
	}
	public String content;//JSON本体
	public String name; // 同じクラス内で衝突しないように決める。
	public String className;
	public String fields; //このJSONに含まれるfield Nameのリスト、カンマ区切り
	public String version;
	
	//DBの結果を読み込む
	public void read(ResultSet r) throws SQLException {
		name = r.getString("Name");
		content = r.getString("Content");
		className = r.getString("ClassName");
		fields = r.getString("Fields");
		version = r.getString("version");
	}

	
	public String getUpdateSQL() {
		if (removed && isNew()) {
			return null;//DBに未登録のまま削除
		}

		//group_codeがあるとき条件に付ける。
		String str_conds = "";
		if (Tool.group_code.length() != 0) {
			str_conds = " and \"GroupCode\"='" + esq(Tool.group_code) +"'";
		}
		if (version != null && version.length() > 0) {
			str_conds += " and \"Version\"='" + version +"'";
		}

		if (removed) {
			return "delete from \"tbl_JSONRecord\" where \"ClassName\"='" + className 
					+ "' and \"Name\"='" + name + "'" + str_conds;
		}

		if (isNew()) {
			return "insert into \"tbl_JSONRecord\" (\"Name\", \"ClassName\", \"Fields\", \"Content\", \"GroupCode\", \"Version\") " 
					+ "values ('" + name + "','" + className + "','" + fields + "','" + _content() + "','" + esq(Tool.group_code) + "','" + version + "')" ;
		} else if (isUpdated()) {
			return "update \"tbl_JSONRecord\" set \"Content\"='" + _content() + "', \"Fields\"='" + fields  
					+ "' where \"Name\"='" + name + "' and \"ClassName\"='" + className + "'" + str_conds;
		}
		return null;
	}
	
	//登録時の特殊文字対策
	private String _content() {
		return esq(content);
	}
	
	public static JSONRecord getJSONRec(String className, String name) {
		JSONRecord t_rec = s_map.get(className + "@" + name);
		if (t_rec == null) {
			t_rec = Tool._db().getJSONRecord(className, name, Tool.version);
		}
		return t_rec;
	}
	
	public static void updatingJSONRec(JSONRecord rec) {
		s_map.put(rec.className + "@" + rec.name, rec);
	}
}