package org.pp.modules.dev.model;

import java.util.Date;

import org.pp.modules.dev.base.BaseField;
import org.pp.modules.dev.service.ModelsService;
import org.pp.utils.DateUtil;
import org.pp.utils.SecurityUtil;

import com.jfinal.kit.StrKit;

import org.pp.modules.dev.model.Models;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Field extends BaseField<Field> {
	public static String TYPE_RELATION = "relation";
	public static String TYPE_DICT = "dict";
	public static String TYPE_NUMBER = "number";
	public static String TYPE_STRING = "string";
	public static String TYPE_TEXT = "text";
	public static String TYPE_DATE = "date";
	public static String TYPE_DATETIME = "datetime";
	public static String TYPE_HTML = "html";
	public static String TYPE_FILE = "file";
	
	private Models model;

	public Models getModel() {
		if(model == null) {
			model = ModelsService.dao.findById(getModelId());
		}
		return model;
	}

	public void setModel(Models model) {
		this.model = model;
	}
	
	public boolean isNullable() {
		return "1".equals(getNullable());
	}
	
	public Object calcDefault() {
		String defaults = getDefaults();
		String type = getType();
		if(Field.TYPE_DATE.equalsIgnoreCase(type)) {
			if("now".equalsIgnoreCase(defaults) || "now()".equalsIgnoreCase(defaults)) {
				return new Date();
			}else {
				return DateUtil.from(defaults, DateUtil.DATE_FORMAT);
			}
		}else if(Field.TYPE_DATETIME.equalsIgnoreCase(type)) {
			if("now".equalsIgnoreCase(defaults) || "now()".equalsIgnoreCase(defaults)) {
				return new Date();
			}else {
				return DateUtil.from(defaults, DateUtil.DATETIME_FORMAT);
			}
		}else if(Field.TYPE_STRING.equalsIgnoreCase(type)) {
			String pref = "random:";
			if(defaults.toLowerCase().startsWith(pref)) {
				int length = Integer.parseInt(defaults.substring(pref.length()));
				defaults = StrKit.getRandomUUID();
				if(defaults.length() > length) {
					defaults = defaults.substring(0,length);
				}
			}
		}else{
			String pref = "session.";
			if(defaults.toLowerCase().startsWith(pref)) {
				String dv = defaults.substring(pref.length()).toLowerCase();
				switch(dv) {
					case "user":
					case "userid":
					case "user.id":
						return SecurityUtil.userId();
					case "user.nickname":
					case "nickname":
						return SecurityUtil.user().getNickname();
					case "department":
					case "deprat":
					case "depratId":
						return SecurityUtil.user().getDepartId();
					default:
						break;
				}
			}
		}
		return defaults;
	}
}
