package cc.smtweb.framework.core.db.impl;

import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.util.JsonUtil;
import cc.smtweb.framework.core.util.NumberUtil;
import cc.smtweb.framework.core.util.jackson.BaseBeanSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by Akmm at 2016-02-23 9:31
 * bean基类，基于Map，
 */
@JsonSerialize(using = BaseBeanSerializer.class)
public class BaseBean implements Serializable {
    protected SwMap data = new SwMap();

    public SwMap getData() {
        return data;
    }

    public void setData(SwMap data) {
        this.data = data;
    }

    @Override
    public BaseBean clone() throws CloneNotSupportedException {
        BaseBean bean = (BaseBean) super.clone();
        bean.data = new SwMap();
        bean.getData().putAll(this.data);
        return bean;
    }

    public boolean isEmpty() {
        return data.isEmpty();
    }

    public String getStr(String fieldName) {
        return getStr(fieldName, "");
    }

    public String getStr(String fieldName, String defValue) {
        Object o = data.get(fieldName);
        return o != null ? o.toString(): defValue;
    }

    public double getDouble(String fieldName) {
        return getDouble(fieldName, 0.0);
    }

    public double getDouble(String fieldName, double defValue) {
        Object o = data.get(fieldName);
        if (o == null) return defValue;
        if (o instanceof Number) return ((Number) o).doubleValue();
        return NumberUtil.getDoubleIgnoreErr(o.toString());
    }

    public int getInt(String fieldName) {
        Object o = data.get(fieldName);
        if (o == null) return 0;
        if (o instanceof Number) return ((Number) o).intValue();
        return NumberUtil.getIntIgnoreErr(o.toString());
    }

    public long getLong(String fieldName) {
        Object o = data.get(fieldName);
        if (o == null) return 0L;
        if (o instanceof Number) return ((Number) o).longValue();
        return NumberUtil.getLongIgnoreErr(o.toString());
    }

    public boolean getBool(String fieldName) {
        Object o = data.get(fieldName);
        if (o == null) return false;
        String v = o.toString();
        return "1".equals(v) || "t".equalsIgnoreCase(v) || "true".equalsIgnoreCase(v);
    }

    public void put(String fieldName, Object value) {
        this.data.put(fieldName, value);
    }

    public void setBool(String fieldName, boolean value) {
        this.data.put(fieldName, value ? 1: 0);
    }

    public Object get(String fieldName) {
        return this.data.get(fieldName);
    }

    public void readFromJson(String json) {
        Map map = JsonUtil.parseMap(json);
        if (map != null) {
            data.putAll(map);
        }
    }

    public void readFromMap(SwMap map) {
        data.putAll(map);
    }
}
