/*
 * Copyright 2019 Ververica GmbH.
 *
 * Licensed 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 com.ververica.statefun.flink.common.protobuf;

import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;

import com.google.protobuf.DescriptorProtos;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.BeforeClass;
import org.junit.Test;

public class ProtobufDescriptorMapTest {

  private static final String TEST_DESCRIPTOR_NAME = "test-descriptors.bin";
  private static DescriptorProtos.FileDescriptorSet FILE_DESCRIPTOR_SET;

  @BeforeClass
  public static void setup() throws IOException {
    // Load the test file descriptor set
    InputStream descriptorStream =
        ProtobufDescriptorMap.class.getClassLoader().getResourceAsStream(TEST_DESCRIPTOR_NAME);
    FILE_DESCRIPTOR_SET = DescriptorProtos.FileDescriptorSet.parseFrom(descriptorStream);
  }

  @Test
  public void exampleUsage() {
    ProtobufDescriptorMap map = ProtobufDescriptorMap.from(FILE_DESCRIPTOR_SET);

    assertThat(map.getDescriptorByName("com.ververica.test.NestedMessage"), isPresent());
    assertThat(map.getDescriptorByName("com.ververica.test.Non Existing Type"), not(isPresent()));
  }

  @Test
  public void includedTypeIsVisible() {
    ProtobufDescriptorMap map = ProtobufDescriptorMap.from(FILE_DESCRIPTOR_SET);

    assertThat(map.getDescriptorByName("google.protobuf.Any"), isPresent());
  }

  @Test
  public void enumsAreVisible() {
    ProtobufDescriptorMap map = ProtobufDescriptorMap.from(FILE_DESCRIPTOR_SET);

    assertThat(map.getDescriptorByName("com.ververica.test.Letter"), isPresent());
  }

  private static <T> Matcher<Optional<T>> isPresent() {
    return new TypeSafeMatcher<Optional<T>>() {
      @Override
      protected boolean matchesSafely(Optional<T> t) {
        return t.isPresent();
      }

      @Override
      public void describeTo(Description description) {
        description.appendText("A present j.u.Optional");
      }
    };
  }
}