package com.lanyuanxiaoyao.bookstore.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.bookstore.entity.Line;
import com.lanyuanxiaoyao.bookstore.entity.QLine;
import com.lanyuanxiaoyao.bookstore.repository.LineRepository;
import com.lanyuanxiaoyao.service.template.entity.IdOnlyEntity;
import com.lanyuanxiaoyao.service.template.service.SimpleServiceSupport;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class LineService extends SimpleServiceSupport<Line> {
  private final LineRepository lineRepository;

  private final ChapterService chapterService;

  public LineService(LineRepository repository, ChapterService chapterService) {
    super(repository);
    this.lineRepository = repository;
    this.chapterService = chapterService;
  }

  @Transactional(rollbackFor = Throwable.class)
  public void load(Long chapterId, String text) {
    var chapter = chapterService.detailOrThrow(chapterId);
    var lines = Stream.of(text.split("\n"))
        .map(StrUtil::trimToNull)
        .filter(ObjectUtil::isNotNull)
        .toList();
    for (int index = 0; index < lines.size(); index++) {
      var line = new Line();
      line.setSequence(NumberUtil.toDouble(index));
      line.setText(lines.get(index));
      line.setChapter(chapter);
      lineRepository.save(line);
    }
  }

  @Transactional(rollbackFor = Throwable.class)
  public void empty(Long chapterId) {
    repository.delete((root, query, builder) -> builder.equal(root.get(Line.Fields.chapter).get(IdOnlyEntity.Fields.id), chapterId));
  }

  @Transactional(rollbackFor = Throwable.class)
  public void generateSequence(Long chapterId) {
    var lines = lineRepository.findAll(
        QLine.line.chapter().id.eq(chapterId),
        QLine.line.sequence.asc()
    );
    for (int index = 0; index < lines.size(); index++) {
      lines.get(index).setSequence(NumberUtil.toDouble(index));
    }
    lineRepository.saveAll(lines);
  }
}

