package dev.ksan.etfoglasiserver.util;

import dev.ksan.etfoglasiserver.model.Subject;
import dev.ksan.etfoglasiserver.model.SubjectAlt;
import dev.ksan.etfoglasiserver.service.SubjectAltService;
import dev.ksan.etfoglasiserver.service.SubjectService;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class SubjectLoader {

  @Autowired SubjectService service;

  @Autowired SubjectAltService altService;
  private static final String URLSubjects = "http://localhost:8080/api/subjects";


  private List<List<String>> alts = new ArrayList<>();

  public void loadAlts() {
    for (List<String> list : alts) {
      Subject subject = service.getSubject(list.getFirst());

      for (String item : list) altService.addSubjectAlt(new SubjectAlt(item, subject));
    }
  }

  public void loadSubjects() {

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

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

    try (BufferedReader reader = new BufferedReader(new FileReader("./init/subjects.txt"))) {

      String line;
      int counter = 0;
      while ((line = reader.readLine()) != null) {
        this.alts.add(new ArrayList<>());

        String[] parts = line.split("\\|");
        for (int i = 0; i < parts.length; i++) {
          if (i == 0) {
            subjects.add(parts[i]);
          } else if (i == 1) {
            codes.add(parts[i]);
          } else {
            this.alts.get(counter).add(parts[i]);
          }
        }

        counter++;
      }

    } catch (IOException e) {
      throw new RuntimeException("Subjects file now found.");
    }

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    try {
      for (String name : subjects) {
        String json = "{ \"name\": \"" + name + "\", \"code\": \"\" }";
        HttpEntity<String> request = new HttpEntity<>(json, headers);
        restTemplate.postForObject(URLSubjects, request, Void.class);
        System.out.println("Added subject: " + name);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
