package com.pingcap.community.blogserver.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

@Slf4j(topic = "job-service")
@Service
@AllArgsConstructor
public class JobService {

  private final PostInfoService postInfoService;

  private final AwardService awardService;

  private final RepostService repostService;

  @Async
  public void triggerGeneratePostTextJob() {
    StopWatch sw = new StopWatch();
    log.info("Start to generate post text.");

    sw.start("Generate post raw text");
    postInfoService.batchGeneratePostRawText();
    sw.stop();

    sw.start("Generate post markdown text");
    postInfoService.batchGeneratePostMarkdownText();
    sw.stop();

    sw.start("Generate post HTML text");
    postInfoService.batchGeneratePostHTMLText();
    sw.stop();

    log.info("Finish to generate post text, cost: {}s.", sw.getTotalTimeSeconds());
  }

  @Async
  public void triggerCalcPostScoreJob() {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start("Calc post score job");
    log.info("Start to calc post score job.");
    int cnt = postInfoService.calcPostsScore();
    stopWatch.stop();
    log.info("Finish to calc post score job, handle: {}, cost: {}s.", cnt, stopWatch.getTotalTimeSeconds());
  }

  @Async
  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void triggerAwardPostAgainJob() {
    StopWatch sw = new StopWatch();
    sw.start("Extra post again job");
    log.info("Start to batch extra award post.");
    awardService.awardPublishedPostsAgain();
    sw.stop();
    log.info("Finished batch extra award posts, cost: {}s.", sw.getTotalTimeSeconds());
  }

  @Async
  public void triggerRepostJob() {
    StopWatch sw = new StopWatch();
    sw.start();
    log.info("Start to repost job.");
    repostService.repostPosts();
    sw.stop();
    log.info("Finish to repost posts job, cost: {}s.", sw.getTotalTimeSeconds());
  }

}
