package com.pcloud.book.util.common;

import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.book.dto.BookFundDto;
import com.pcloud.book.elasticsearch7.entity.Es7Book;
import com.pcloud.book.elasticsearch7.entity.Es7BookFund;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.cglib.beans.BeanCopier;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Converter {

    private Converter() {}

    private static final BeanCopier BOOK_COPIER = BeanCopier.create(Es7Book.class, BookDto.class, false);
    private static final BeanCopier FUND_COPIER = BeanCopier.create(Es7BookFund.class, BookFundDto.class, false);

    public static BookDto convert(Es7Book book) {
        if (book == null) {
            return null;
        }
        BookDto dto = new BookDto();
        BOOK_COPIER.copy(book, dto, null);

        if (CollectionUtils.isNotEmpty(book.getBookFundList())) {
            List<BookFundDto> funds = new ArrayList<>();
            book.getBookFundList().forEach((f) -> {
                BookFundDto fundDto = new BookFundDto();
                FUND_COPIER.copy(f, fundDto, null);
                funds.add(fundDto);
            });
            funds.sort(Comparator.comparing(BookFundDto::getStartTime).reversed());
            dto.setBookFunds(funds);
        }

        return dto;
    }
}
