package foundation.icall.stamp;

import java.util.Date;

import foundation.dao.Filter;
import foundation.data.entity.Entity;
import foundation.data.object.DataObject;
import foundation.data.object.EntitySaver;
import foundation.icall.ICall;
import foundation.persist.NamedSQL;
import foundation.persist.SQLRunner;
import foundation.persist.source.NamedDataSource;
import foundation.util.Util;

public class Stamp {

	private ICall iCall;
	private NamedDataSource remoteSource;
	private Date localValue;
	private Date remoteValue;
	private boolean active;
	private boolean needClearHistory;
	
	public Stamp() {
		needClearHistory = false;
	}
	
	public void init(ICall iCall, NamedDataSource remoteSource) {
		this.iCall = iCall;
		this.remoteSource = remoteSource;
		active = false;
		localValue = null;
		remoteValue = null;
	}

	public void load() throws Exception {
		//1. 如果没有配置时间戳字段,不需要加载
		String stampField = iCall.getStampField();
		
		if (Util.isEmpty(stampField)) {
			active = false;
			needClearHistory = true;
			return;
		}
		
		//2. 加载本地时间戳
		loadLocal();
		
		//3. 加载远程时间戳
		loadRemote();
		
		//4.
		active = (localValue != null) && (remoteValue != null);
	}
	
	public void loadLocal() throws Exception {
		String callId = iCall.getId();
		
		DataObject dataObject = DataObject.getInstance("sys_interface_stamp");
		Entity entity = dataObject.getTableEntity(new Filter("interface_id", callId));
		
		if (iCall.isPermitEmptyStamp() && entity == null) {
			return;
		}
		
		Date value = new Date(0);
		
		if (entity == null) {
			EntitySaver saver = dataObject.createEntitySaver();
			saver.set("id", callId);
			saver.set("interface_id", callId);
			saver.set("stamp_time", value);
			saver.insert();
			
			needClearHistory = true;
		}
		else {
			value = entity.getDate("stamp_time", null);
			
			if (value == null) {
				value = new Date(0);
				needClearHistory = true;
			}
		}
		
		localValue = value;
	}
	
	public void saveLocal() throws Exception {
		if (!active) {
			return;
		}
		
		DataObject dataObject = DataObject.getInstance("sys_interface_stamp");
		EntitySaver saver = dataObject.createEntitySaver();
		
		String iCallId = iCall.getId();
		
		saver.set("id", iCallId);
		saver.set("interface_id", iCallId);
		saver.set("stamp_time", remoteValue);
		saver.update();
	}	
	
	public void loadRemote() throws Exception {
		NamedSQL namedSQL = NamedSQL.getInstance(remoteSource.getDBaseType(), "getMaxRemoteStamp");
		namedSQL.setParam("tableName", iCall.getURL());
		namedSQL.setParam("fieldName", iCall.getStampField());
		remoteValue = SQLRunner.getDate(remoteSource, namedSQL);
	}
	
	public boolean isNeedClearHistory() {
		return needClearHistory;
	}

	public boolean isActive() {
		return active;
	}

	public Date getLocalValue() {
		return localValue;
	}
	
	public String getLocalValueString() {
		return Util.DataTimeToString(localValue);
	}
	
	public Date getRemoteValue() {
		return remoteValue;
	}

}