/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
 * file distributed with this work for additional information regarding copyright ownership. The ASF 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.apache.tuweni.scuttlebutt.lib;

import static org.apache.tuweni.scuttlebutt.lib.Utils.connectWithInvite;
import static org.apache.tuweni.scuttlebutt.lib.Utils.getMasterClient;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import org.apache.tuweni.concurrent.AsyncResult;
import org.apache.tuweni.crypto.sodium.Sodium;
import org.apache.tuweni.junit.VertxExtension;
import org.apache.tuweni.junit.VertxInstance;
import org.apache.tuweni.scuttlebutt.Invite;

import io.vertx.core.Vertx;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(VertxExtension.class)
class InviteTest {

  @BeforeAll
  static void checkSodium() {
    assumeTrue(Sodium.isAvailable(), "Sodium native library is not available");
  }

  /**
   * Tests that it is possible to generate a test invite code.
   */
  @Test
  void testGenerateInvite(@VertxInstance Vertx vertx) throws Exception {
    ScuttlebuttClient scuttlebuttClient = getMasterClient(vertx);

    AsyncResult<Invite> inviteAsyncResult = scuttlebuttClient.getNetworkService().generateInviteCode(10000);

    Invite invite = inviteAsyncResult.get();

    AsyncResult<Invite> inviteAsyncResult2 = scuttlebuttClient.getNetworkService().generateInviteCode(10000);

    Invite invite2 = inviteAsyncResult2.get();

    assertEquals(invite.identity().publicKeyAsBase64String(), invite2.identity().publicKeyAsBase64String());
  }

  /**
   * Tests it's possible to request the server uses an invite code generated by another node.
   */
  @Disabled("will not work with CI right now")
  @Test
  void testUseInvite(@VertxInstance Vertx vertx) throws Exception {
    ScuttlebuttClient masterClient = getMasterClient(vertx);
    AsyncResult<Invite> inviteAsyncResult = masterClient.getNetworkService().generateInviteCode(10000);

    ScuttlebuttClient scuttlebuttClient = connectWithInvite(vertx, inviteAsyncResult.get());
    assertNotNull(scuttlebuttClient);
  }

}
