package cn.estsh.i3plus.pojo.aps.validator;

import cn.estsh.i3plus.pojo.aps.annotation.CalendarTimeAnntation;
import cn.estsh.i3plus.pojo.aps.model.TimeBlock;
import cn.estsh.i3plus.pojo.base.util.StringUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class CalendarTimeValidator implements ConstraintValidator<CalendarTimeAnntation, String> {
    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        for (String strTime : s.split(",")) {
            if (StringUtil.isEmpty(strTime)) {
                continue;
            }

            String[] times = strTime.split("~");
            if (times.length == 1) {
                try {
                    timeFormat.parse(times[0]);
                } catch (ParseException e) {
                    return false;
                }
            } else if (times.length == 2) {
                try {
                    TimeBlock timeBlock = new TimeBlock();
                    timeBlock.setBegin(timeFormat.parse(times[0]));
                    timeBlock.setEnd(timeFormat.parse(times[1]));
                } catch (ParseException e) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }
}
