/*
 * Copyright 2022 Google LLC
 *
 * 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.example.stitcher;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;

import com.google.cloud.testing.junit4.MultipleAttemptsRule;
import com.google.cloud.video.stitcher.v1.LiveAdTagDetail;
import com.google.cloud.video.stitcher.v1.LiveSession;
import com.google.cloud.video.stitcher.v1.VideoStitcherServiceClient.ListLiveAdTagDetailsPagedResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class LiveSessionTest {

  @Rule
  public final MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(5);
  private static final String SLATE_ID = TestUtils.getSlateId();
  private static final String LIVE_CONFIG_ID = TestUtils.getLiveConfigId();
  private static String LIVE_CONFIG_NAME;
  private static String LIVE_SESSION_NAME_PREFIX;
  private static String LIVE_SESSION_NAME;
  private static String SESSION_ID;
  private static String AD_TAG_DETAIL_NAME;
  private static String AD_TAG_DETAIL_ID;
  private static String STITCH_DETAIL_NAME;
  private static String STITCH_DETAIL_ID;
  private static String PROJECT_ID;
  private static PrintStream originalOut;
  private static ByteArrayOutputStream bout;

  private static String requireEnvVar(String varName) {
    String varValue = System.getenv(varName);
    assertNotNull(
        String.format("Environment variable '%s' is required to perform these tests.", varName));
    return varValue;
  }

  @BeforeClass
  public static void beforeTest()
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
    PROJECT_ID = requireEnvVar("GOOGLE_CLOUD_PROJECT");

    originalOut = System.out;
    bout = new ByteArrayOutputStream();
    System.setOut(new PrintStream(bout));

    TestUtils.cleanStaleSlates(PROJECT_ID, TestUtils.LOCATION);
    TestUtils.cleanStaleLiveConfigs(PROJECT_ID, TestUtils.LOCATION);

    // Project number is always returned in the live session name
    LIVE_SESSION_NAME = String.format("locations/%s/liveSessions/", TestUtils.LOCATION);
    CreateSlate.createSlate(PROJECT_ID, TestUtils.LOCATION, SLATE_ID, TestUtils.SLATE_URI);
    CreateLiveConfig.createLiveConfig(PROJECT_ID, TestUtils.LOCATION, LIVE_CONFIG_ID,
        TestUtils.LIVE_URI, TestUtils.LIVE_AD_TAG_URI, SLATE_ID);

    // Session IDs are autogenerated.
    LIVE_SESSION_NAME_PREFIX = String.format("locations/%s/liveSessions/", TestUtils.LOCATION);
    LiveSession sessionResponse =
        CreateLiveSession.createLiveSession(PROJECT_ID, TestUtils.LOCATION, LIVE_CONFIG_ID);
    assertThat(sessionResponse.getName(), containsString(LIVE_SESSION_NAME_PREFIX));

    LIVE_SESSION_NAME = sessionResponse.getName();
    String[] id = LIVE_SESSION_NAME.split("/");
    SESSION_ID = id[id.length - 1];

    // To get ad tag details, you need to curl the main manifest and
    // a rendition first. This supplies media player information to the API.
    //
    // Curl the playUri first. The last line of the response will contain a
    // renditions location. Curl the live session name with the rendition
    // location appended.

    String playUri = sessionResponse.getPlayUri();
    assertNotNull(playUri);
    String renditions = TestUtils.getRenditions(playUri);
    assertNotNull(renditions);

    // playUri will be in the following format:
    // https://videostitcher.googleapis.com/v1/projects/{project}/locations/{location}/liveSessions/{session-id}/manifest.m3u8?signature=...
    // Replace manifest.m3u8?signature=... with the renditions location.
    String renditionsUri =
        String.format("%s/%s", playUri.substring(0, playUri.lastIndexOf("/")), renditions);
    TestUtils.connectToRenditionsUrl(renditionsUri);

    ListLiveAdTagDetailsPagedResponse adtagResponse =
        ListLiveAdTagDetails.listLiveAdTagDetails(PROJECT_ID, TestUtils.LOCATION, SESSION_ID);
    for (LiveAdTagDetail liveAdTagDetail : adtagResponse.iterateAll()) {
      AD_TAG_DETAIL_NAME = liveAdTagDetail.getName();
    }
    id = AD_TAG_DETAIL_NAME.split("/");
    AD_TAG_DETAIL_ID = id[id.length - 1];
  }

  @Test
  public void testGetLiveSession() throws IOException {
    LiveSession response = GetLiveSession.getLiveSession(PROJECT_ID, TestUtils.LOCATION,
        SESSION_ID);
    assertThat(response.getName(), containsString(LIVE_SESSION_NAME));
  }

  @Test
  public void testListLiveAdTagDetailsTest() throws IOException {
    ListLiveAdTagDetailsPagedResponse response =
        ListLiveAdTagDetails.listLiveAdTagDetails(PROJECT_ID, TestUtils.LOCATION, SESSION_ID);

    Boolean pass = false;
    for (LiveAdTagDetail liveAdTagDetail : response.iterateAll()) {
      if (liveAdTagDetail.getName().contains(LIVE_SESSION_NAME.concat("/liveAdTagDetails/"))) {
        pass = true;
        break;
      }
    }
    assert (pass);
  }

  @Test
  public void testGetLiveAdTagDetailTest() throws IOException {
    LiveAdTagDetail response =
        GetLiveAdTagDetail.getLiveAdTagDetail(
            PROJECT_ID, TestUtils.LOCATION, SESSION_ID, AD_TAG_DETAIL_ID);
    assertThat(response.getName(), containsString(AD_TAG_DETAIL_NAME));
  }

  @After
  public void tearDown() {
    bout.reset();
  }

  @AfterClass
  public static void afterTest()
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // No delete method for live sessions
    DeleteLiveConfig.deleteLiveConfig(PROJECT_ID, TestUtils.LOCATION, LIVE_CONFIG_ID);
    String deleteResponse = bout.toString();
    assertThat(deleteResponse, containsString("Deleted live config"));
    bout.reset();

    DeleteSlate.deleteSlate(PROJECT_ID, TestUtils.LOCATION, SLATE_ID);
    deleteResponse = bout.toString();
    assertThat(deleteResponse, containsString("Deleted slate"));

    System.out.flush();
    System.setOut(originalOut);
  }
}
