package hozza.network.crons.twitch;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

import com.vaadin.flow.spring.annotation.SpringComponent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import hozza.network.models.twitch.entities.MariaPerson;
import hozza.network.models.twitch.entities.MariaStreamer;
import hozza.network.models.twitch.entities.MariaWatching;
import hozza.network.models.twitch.repositories.MariaPersonRepository;
import hozza.network.models.twitch.repositories.MariaStreamerRepository;
import hozza.network.models.twitch.repositories.MariaWatchingRepository;
import hozza.network.security.threading.database.TwitchCronThreadManager;

@SpringComponent
public class TwitchService
{
    private final MariaPersonRepository personRepository;
    private final MariaStreamerRepository streamerRepository;
    private final MariaWatchingRepository watchingRepository;
    private final AtomicInteger possibleEntries;

    @Autowired
    public TwitchService(MariaPersonRepository personRepository, MariaStreamerRepository streamerRepository, MariaWatchingRepository watchingRepository) {
        this.personRepository = personRepository;
        this.streamerRepository = streamerRepository;
        this.watchingRepository = watchingRepository;
        this.possibleEntries = new AtomicInteger(0);
    }

    @Scheduled(cron =  "0 0 * * * *")
    public void statCron()
    {
        this.possibleEntries.set(0);
        final ZonedDateTime starting = ZonedDateTime.now(ZoneId.of("CET"));
        System.out.println("[MARIADB] CRON STARTED "+starting);

        List<MariaPerson> viewers = Collections.synchronizedList(personRepository.findAll());
        List<MariaStreamer> streamers = Collections.synchronizedList(streamerRepository.findAll());
        List<MariaWatching> watchingToSave = Collections.synchronizedList(new ArrayList<>());

        TwitchCronThreadManager manager = new TwitchCronThreadManager();

        List<Callable<Boolean>> taskList = new ArrayList<>();

        System.out.println("[MARIADB] PREPARATIONS DONE "+ZonedDateTime.now(ZoneId.of("CET")));

        for(MariaStreamer streamer : streamers)
        {
            TwitchServiceCallable r = new TwitchServiceCallable(streamer, viewers, starting, personRepository, watchingToSave, possibleEntries);
            taskList.add(r);
        }

        manager.invokeCallableList(taskList);
        this.watchingRepository.saveAll(watchingToSave);
        System.out.println("[MARIADB] STREAMERS SAVED | POSSIBLE ENTRIES: "+this.possibleEntries.get()+" | GOT: "+watchingToSave.size()+" | COMPLETED: "+ZonedDateTime.now(ZoneId.of("CET")));
    }
}
