package tv.pluto;

import io.qameta.allure.Description;
import io.qameta.allure.TmsLink;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import tv.pluto.core.BaseTest;
import tv.pluto.grpc.gracenoteruns.GracenoteRunsClient;
import tv.pluto.mongo.entities.gracenoruns.GracenoteRuns;
import tv.pluto.mongo.utils.GracenoteRunsUtils;
import tv.pluto.utils.CommonUtils;

public class GracenoteRunsTestSuite extends BaseTest {
  private GracenoteRunsUtils gracenoteRunsUtils;
  private GracenoteRunsClient gracenoteRunsClient;

  @BeforeClass(alwaysRun = true)
  private void setUp() {
    gracenoteRunsUtils = new GracenoteRunsUtils();
    gracenoteRunsClient = new GracenoteRunsClient(grpcChannelManager.getChannel());
  }

  @Test
  @Description("CFeedsSyncAllIds - stream returns CFEEDS stream of GracenoteRuns ids")
  @TmsLink("28501804")
  public void C28501804_TEST() {
    Iterator<?> gracenoteIterator =
        gracenoteRunsClient.getCFeedsResponse(null, null, null, "cFeedsSyncAllIds");
    List<String> grpcIds = new ArrayList<>();
    int total = 0;
    while (gracenoteIterator.hasNext() && total < 100) {
      String id =
          ((tv.pluto.ip.dal.gracenoteruns.GracenoteRuns.Id) gracenoteIterator.next()).getId();
      grpcIds.add(id);
      total++;
    }

    List<?> mongoIds = gracenoteRunsUtils.getDocumentsByIds(grpcIds);
    Assert.assertTrue(grpcIds.size() > 0);
    Assert.assertEquals(grpcIds.size(), mongoIds.size());
  }

  @Test
  @Description("cFeedsSyncDocuments - last_run_at")
  @TmsLink("28501805")
  public void C28501805_TEST() {
    LocalDateTime ranAt = LocalDateTime.now(ZoneOffset.UTC).minusWeeks(30);
    Iterator<?> cFeedsSyncAllIds =
        gracenoteRunsClient.getCFeedsResponse(null, ranAt + "Z", null, "cFeedsSyncDocuments");
    Assert.assertTrue(cFeedsSyncAllIds.hasNext());

    while (cFeedsSyncAllIds.hasNext()) {
      GracenoteRuns grpcCracenoteRuns =
          gracenoteRunsUtils.mapGrpcObjectToPojo(cFeedsSyncAllIds.next(), GracenoteRuns.class);
      LocalDateTime grpcTime = grpcCracenoteRuns.getCreatedAt();
      boolean isTrue = ranAt.isBefore(grpcTime) || ranAt.equals(grpcTime);
      Assert.assertTrue(isTrue);
    }
  }

  @Test(
      expectedExceptions = RuntimeException.class,
      expectedExceptionsMessageRegExp = NOT_FOUND_MESSAGE)
  @Description("cFeedsSyncDocuments - last_run_at future time")
  @TmsLink("28501806")
  public void C28501806_TEST() {
    String futureTime = CommonUtils.localDateTimeStringPlusDays(2);
    gracenoteRunsClient.getCFeedsResponse(null, futureTime, null, "cFeedsSyncDocuments").next();
  }
}
