package com.sourcefellows.patterns.steadystate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableScheduling
public class AttendeeApplication {

    private static final Logger log = LoggerFactory.getLogger(AttendeeApplication.class);
    @Autowired
    private AttendeeRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(AttendeeApplication.class, args);
    }

    @Bean
    public CommandLineRunner printAttendees(AttendeeRepository repository) {
        return (args) -> {

            int elementCount = (int) repository.count();
            int pageSize = 10;
            for (int pageNumber = 0;
                 pageNumber <= elementCount / pageSize;
                 pageNumber++) {

                Pageable request = PageRequest.of(pageNumber, pageSize);
                repository.findAll(request).forEach(attendee -> {
                    System.out.println(attendee.toString());
                });
            }
            System.out.println("end");

        };
    }

    @Scheduled(fixedRate = 12, timeUnit = TimeUnit.HOURS)
    public void cleanDB() {
        System.out.println("cleanDB");
        LocalDate date = LocalDate.now().minusDays(30);
        repository.deleteAttendeeByCreationDateBefore(date);
    }

}
