package mobos.leoss.si.qsystemmobileapp.SupportClasses;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Blaz on 10. 06. 2016.
 */
public class DateDeserializer implements JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json == null) {
            return null;
        }
        String jsonString = json.getAsJsonPrimitive().getAsString();
        //Go to https://regex101.com Test this regexp \/Date\((\-?\d*?)([\+\-]\d*)?\)\/
        // /Date(12345678989-0000)/ o /Date(12345678989+0000)/
        // /Date(-12345678989-0000)/ o /Date(-12345678989+0000)/
        // /Date(-12345678989)/ o /Date(-12345678989)/
        String regexp = "\\/Date\\((\\-?\\d*?)([\\+\\-]\\d*)?\\)\\/";
        Pattern myPattern = Pattern.compile(regexp);
        Matcher myMatcher = myPattern.matcher(jsonString);
        if (!myMatcher.matches()) {
            return null;
        }
        int groupCount = myMatcher.groupCount();
        if (groupCount > 0) {
            return new Date(Long.valueOf(myMatcher.group(1)));
        } else {
            return null;
        }
        //spodnje uporabi če ne želiš upoštevati razlike v TimeZone-u
        /*if (groupCount > 1 && myMatcher.group(2) != null && (myMatcher.group(2).contains("+") || myMatcher.group(2).contains("-"))) {
            return new Date(Long.valueOf(myMatcher.group(1)) - TimeZone.getDefault().getRawOffset() + Long.valueOf(myMatcher.group(2)) * 60 * 60 * 10);
        } else if (groupCount > 0) {
            return new Date(Long.valueOf(myMatcher.group(1)) - TimeZone.getDefault().getRawOffset());
        } else {
            return null;
        }*/

        //obsolete
        /*String s = json.getAsJsonPrimitive().getAsString();
        long l = Long.parseLong(s.substring(s.indexOf("(") + 1, s.indexOf("+")));
        return new Date(l);*/
    }
}
