package com.bonus.common.houqin.framework.config.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TimeDeserializer extends JsonDeserializer<LocalTime> {
   public static final String HH_MM_SS = "HH$1mm$2ss$3";
   public static final String HH_MM = "HH$1mm$2";
   public static final String HH = "HH$1";
   private static final Map<String, Pattern> patternMap = Maps.newLinkedHashMap();

   public static void main(String[] args) {
      System.out.println(getPattern("11:11:11"));
      System.out.println(getPattern("11点11分"));
      System.out.println(getPattern("11点"));
      System.out.println(getPattern("11"));
   }

   private static String getPattern(String dateString) {
      Iterator var1 = patternMap.entrySet().iterator();

      while(var1.hasNext()) {
         Map.Entry<String, Pattern> entry = (Map.Entry)var1.next();
         Matcher matcher = ((Pattern)entry.getValue()).matcher(dateString);
         if (matcher.find()) {
            if ("HH$1mm$2ss$3".equals(entry.getKey())) {
               return "HH$1mm$2ss$3".replace("$1", matcher.group(1)).replace("$2", matcher.group(2)).replace("$3", matcher.group(3));
            }

            if ("HH$1mm$2".equals(entry.getKey())) {
               return "HH$1mm$2".replace("$1", matcher.group(1)).replace("$2", matcher.group(2));
            }

            if ("HH$1".equals(entry.getKey())) {
               return "HH$1".replace("$1", matcher.group(1));
            }
         }
      }

      return null;
   }

   @Override
   public LocalTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
      if (StringUtils.isBlank(p.getText())) {
         return null;
      } else {
         String pattern = getPattern(p.getText());
         if (pattern == null) {
            throw new RuntimeException("不支持的时间格式:" + p.getText());
         } else {
            return LocalTime.parse(p.getText(), DateTimeFormatter.ofPattern(pattern));
         }
      }
   }

   static {
      patternMap.put("HH$1mm$2ss$3", Pattern.compile("^\\d{1,2}(\\D+)\\d{1,2}(\\D+)\\d{1,2}(\\D?)$"));
      patternMap.put("HH$1mm$2", Pattern.compile("^\\d{1,2}(\\D+)\\d{1,2}(\\D?)$"));
      patternMap.put("HH$1", Pattern.compile("^\\d{1,2}(\\D?)$"));
   }
}
