package ru.ulstu.commit.service;

import org.springframework.stereotype.Service;
import ru.ulstu.commit.model.CommitListDto;
import ru.ulstu.core.model.response.PageableItems;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CommitService {
    private static final String COMMITS_FILE_NAME = "/commits.log";

    private final List<CommitListDto> commits;

    public CommitService() {
        commits = getCommits();
    }

    public PageableItems<CommitListDto> getCommits(int offset, int count) {
        return new PageableItems<>(commits.size(), commits.stream()
                .skip(offset)
                .limit(count)
                .collect(Collectors.toList()));
    }

    private List<CommitListDto> getCommits() {
        return getFileContent()
                .stream()
                .map(CommitListDto::new)
                .filter(Objects::nonNull)
                .sorted((c1, c2) -> c2.getDate().compareTo(c1.getDate()))
                .collect(Collectors.toList());
    }

    private List<String> getFileContent() {

        List<String> result = new ArrayList<>();

        //Get file from resources folder
        InputStream is = getClass().getResourceAsStream(COMMITS_FILE_NAME);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                result.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.reverse(result);
        return result;
    }
}

