package dev.ksan.etfoglasiserver;

import dev.ksan.etfoglasiserver.service.Scraper;
import java.util.Scanner;

import dev.ksan.etfoglasiserver.service.SubjectService;
import dev.ksan.etfoglasiserver.util.SubjectLoader;
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.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class EtfoglasiServerApplication {

  public static void main(String[] args) {
    ApplicationContext context =
            SpringApplication.run(EtfoglasiServerApplication.class, args);

    Scraper scraper = context.getBean(Scraper.class);

    SubjectService subjectService =
            context.getBean(SubjectService.class);

    if (subjectService.count() <= 1) {
      SubjectLoader subjectLoader =
              context.getBean(SubjectLoader.class);

      subjectLoader.loadSubjects();

      System.out.println("Loading...");
      subjectLoader.loadAlts();
    } else {
      System.out.println("Subjects already loaded, skipping...");
    }

    new Thread(scraper).start();
  }


  @Bean
  public CommandLineRunner commandLineRunner(SubjectLoader subjectLoader) {
    return args -> {
      subjectLoader.loadAlts();
      try{
      }catch (Exception e){
        e.printStackTrace();
      }
      subjectLoader.loadAlts();
    };
  }
}
