// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.json;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.util.function.BiFunction;

public class InstantCoercer extends TypeCoercer<Instant> {
  @Override
  public boolean test(Class<?> aClass) {
    return Instant.class.isAssignableFrom(aClass);
  }

  @Override
  public BiFunction<JsonInput, PropertySetting, Instant> apply(Type type) {
    return (jsonInput, setting) -> {
      JsonType token = jsonInput.peek();

      if (JsonType.NUMBER.equals(token)) {
        return Instant.ofEpochMilli(jsonInput.nextNumber().longValue());
      } else if (JsonType.STRING.equals(token)) {
        String raw = jsonInput.nextString();
        try {
          TemporalAccessor parsed = DateTimeFormatter.ISO_INSTANT.parse(raw);
          return Instant.from(parsed);
        } catch (DateTimeParseException ignored) {
          try {
            return Instant.ofEpochMilli(new BigDecimal(raw).longValue());
          } catch (NumberFormatException e) {
            throw new JsonException(raw + " does not look like an Instant");
          }
        }
      }

      throw new JsonException("Unable to parse: " + jsonInput.read(Object.class));
    };
  }
}
