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.gracenote_logs.GracenoteLogsClient;
import tv.pluto.mongo.entities.gracenotelogs.GracenoteLogs;
import tv.pluto.mongo.utils.GracenoteLogsUtils;
import tv.pluto.utils.CommonUtils;

public class GracenoteLogsTestSuite extends BaseTest {
  private GracenoteLogsUtils gracenoteLogsUtils;
  private GracenoteLogsClient gracenoteLogsClient;

  @BeforeClass(alwaysRun = true)
  private void setUp() {
    gracenoteLogsUtils = new GracenoteLogsUtils();
    gracenoteLogsClient = new GracenoteLogsClient(grpcChannelManager.getChannel());
  }

  @Test
  @Description("CFeedsSyncAllIds - stream returns CFEEDS stream of GracenoteLogs ids")
  @TmsLink("28501798")
  public void C28501798_TEST() {
    Iterator<?> gracenoteIterator =
        gracenoteLogsClient.getCFeedsResponse(null, null, null, "cFeedsSyncAllIds");
    List<String> grpcIds = new ArrayList<>();
    for (int i = 0; i < 50; i++) {
      String id =
          ((tv.pluto.ip.dal.gracenotelogs.GracenoteLogs.Id) gracenoteIterator.next()).getId();
      grpcIds.add(id);
    }

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

  @Test
  @Description("cFeedsSyncDocuments - last_run_at")
  @TmsLink("28501799")
  public void C28501799_TEST() {
    LocalDateTime ranAt = LocalDateTime.now(ZoneOffset.UTC).minusMonths(5);
    Iterator<?> cFeedsSyncAllIds =
        gracenoteLogsClient.getCFeedsResponse(null, ranAt + "Z", null, "cFeedsSyncDocuments");
    Assert.assertTrue(cFeedsSyncAllIds.hasNext());
    int total = 0;

    for (int i = 0; i < 10; i++) {
      GracenoteLogs grpcTimeline =
          gracenoteLogsUtils.mapGrpcObjectToPojo(cFeedsSyncAllIds.next(), GracenoteLogs.class);
      LocalDateTime grpcTime = grpcTimeline.getUpdatedAt();
      if (grpcTime != null) {
        boolean isTrue = ranAt.isBefore(grpcTime) || grpcTime.equals(ranAt);
        Assert.assertTrue(isTrue);
        total++;
      }
    }

    Assert.assertTrue(total > 0);
  }

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