package ru.ulstu.paper.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.file.service.FileService;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperFilterDto;
import ru.ulstu.paper.model.PaperStatusDto;
import ru.ulstu.paper.repository.PaperRepository;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static ru.ulstu.core.util.StreamApiUtils.convert;
import static ru.ulstu.paper.model.Paper.PaperStatus.ATTENTION;
import static ru.ulstu.paper.model.Paper.PaperStatus.DRAFT;
import static ru.ulstu.paper.model.Paper.PaperStatus.ON_PREPARATION;

@Service
public class PaperService {
    private final PaperNotificationService paperNotificationService;
    private final PaperRepository paperRepository;
    private final UserService userService;
    private final FileService fileService;


    public PaperService(PaperRepository paperRepository,
                        FileService fileService,
                        PaperNotificationService paperNotificationService,
                        UserService userService) {
        this.paperRepository = paperRepository;
        this.fileService = fileService;
        this.paperNotificationService = paperNotificationService;
        this.userService = userService;
    }

    public List<Paper> findAll() {
        return paperRepository.findAll().stream().sorted((paper1, paper2) -> {
            int statusCompareResult =
                    Integer.valueOf(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper1.getStatus()))
                            .compareTo(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper2.getStatus()));
            if (statusCompareResult != 0) {
                return statusCompareResult;
            }
            return paper1.getTitle().compareTo(paper2.getTitle());
        }).collect(Collectors.toList());
    }

    public List<PaperDto> findAllDto() {
        return convert(findAll(), PaperDto::new);
    }

    @Transactional
    public Integer create(PaperDto paperDto) throws IOException {
        Paper newPaper = copyFromDto(new Paper(), paperDto);
        newPaper = paperRepository.save(newPaper);
        paperNotificationService.sendCreateNotification(newPaper);
        return newPaper.getId();
    }

    private Paper copyFromDto(Paper paper, PaperDto paperDto) throws IOException {
        paper.setComment(paperDto.getComment());
        paper.setCreateDate(paper.getCreateDate() == null ? new Date() : paper.getCreateDate());
        paper.setLocked(paperDto.getLocked());
        paper.setStatus(paperDto.getStatus() == null ? DRAFT : paperDto.getStatus());
        paper.setTitle(paperDto.getTitle());
        paper.setUpdateDate(new Date());
        paper.setDeadlineDate(paperDto.getDeadlineDate());
        if (paperDto.getTmpFileName() != null) {
            paper.setFileData(fileService.createFileFromTmp(paperDto.getTmpFileName()));
        }
        if (paperDto.getAuthors() != null && !paperDto.getAuthors().isEmpty()) {
            paperDto.getAuthors().forEach(authorIds -> paper.getAuthors().add(userService.findById(authorIds.getId())));
        }
        return paper;
    }

    @Transactional
    public Integer update(PaperDto paperDto) throws IOException {
        Paper paper = paperRepository.findOne(paperDto.getId());
        Paper.PaperStatus oldStatus = paper.getStatus();
        if (paperDto.getTmpFileName() != null && paper.getFileData() != null) {
            fileService.deleteFile(paper.getFileData());
        }
        paperRepository.save(copyFromDto(paper, paperDto));

        if (paper.getStatus() != oldStatus) {
            paperNotificationService.statusChangeNotification(paper, oldStatus);
        }

        return paper.getId();
    }

    @Transactional
    public void delete(Integer paperId) throws IOException {
        Paper paper = paperRepository.findOne(paperId);
        if (paper.getFileData() != null) {
            fileService.deleteFile(paper.getFileData());
        }
        paperRepository.delete(paper);
    }

    public List<PaperStatusDto> getPaperStatuses() {
        return convert(Arrays.asList(Paper.PaperStatus.values()), PaperStatusDto::new);
    }

    @Transactional
    public Paper create(String title, User user, Date deadlineDate) {
        Paper paper = new Paper();
        paper.setTitle(title);
        paper.getAuthors().add(user);
        paper.setDeadlineDate(deadlineDate);
        paper.setCreateDate(new Date());
        paper.setUpdateDate(new Date());
        paper.setStatus(DRAFT);
        paper = paperRepository.save(paper);

        paperNotificationService.sendCreateNotification(paper);

        return paper;
    }

    public List<PaperDto> filter(PaperFilterDto filterDto) {
        return convert(paperRepository.filter(userService.findById(filterDto.getAuthorId()), filterDto.getYear()), PaperDto::new);
    }

    public void closeFailedPapers() {
        List<Paper> papers = paperRepository.findAll()
                .stream()
                .filter(paper -> paper.getDeadlineDate() != null
                        && (paper.getStatus() == ON_PREPARATION
                        || paper.getStatus() == DRAFT
                        || paper.getStatus() == ATTENTION)
                        && paper.getDeadlineDate().before(new Date()))
                .collect(Collectors.toList());
        papers.forEach(paper -> {
            Paper.PaperStatus oldStatus = paper.getStatus();
            paper.setStatus(Paper.PaperStatus.FAILED);
            paperRepository.save(paper);
            paperNotificationService.sendFailedNotification(paper, oldStatus);
        });
    }
}
