package cn.com.qmth.stmms.biz.mark.model;

import org.apache.commons.lang3.StringUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * 单个评卷区设置模型
 */
public class MarkConfigItem {

    // 数据库中多个单元紧凑保存的拼接符，兼容旧版本只保存图片序号的模式
    public static final String DB_ITEM_JOINER = ",";

    // 数据库中单个单元紧凑保存的拼接符，兼容旧版本只保存图片序号的模式
    public static final String DB_FIELD_JOINER = ":";

    // 裁切去所属的图片序号，从1开始
    private int i;

    // 裁切区左上角X坐标
    private double x;

    // 裁切区左上角Y坐标
    private double y;

    // 裁切区宽度
    private double w;

    // 裁切区高度
    private double h;

    public MarkConfigItem() {

    }

    public MarkConfigItem(String text) {
        text = StringUtils.trimToEmpty(text);
        String[] values = StringUtils.split(text, DB_FIELD_JOINER);
        try {
            i = Integer.parseInt(values[0]);
            if (values.length > 1) {
                x = Double.parseDouble(values[1]);
            }
            if (values.length > 2) {
                y = Double.parseDouble(values[2]);
            }
            if (values.length > 3) {
                w = Double.parseDouble(values[3]);
            }
            if (values.length > 4) {
                h = Double.parseDouble(values[4]);
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid PictureConfigItem init text:" + text);
        }
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

    public double getW() {
        return w;
    }

    public void setW(double w) {
        this.w = w;
    }

    public double getH() {
        return h;
    }

    public void setH(double h) {
        this.h = h;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(i).append(DB_FIELD_JOINER);
        sb.append(x).append(DB_FIELD_JOINER);
        sb.append(y).append(DB_FIELD_JOINER);
        sb.append(w).append(DB_FIELD_JOINER);
        sb.append(h);
        return sb.toString();
    }

    public static List<MarkConfigItem> parse(String text) {
        List<MarkConfigItem> list = new LinkedList<MarkConfigItem>();
        text = StringUtils.trimToEmpty(text);
        String[] values = StringUtils.split(text, DB_ITEM_JOINER);
        for (String value : values) {
            try {
                MarkConfigItem item = new MarkConfigItem(value);
                if (item != null && item.i > 0) {
                    list.add(item);
                }
            } catch (Exception e) {
                continue;
            }
        }
        return list;
    }

}
