package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"sync"

	"github.com/gocarina/gocsv"
)

type (
	EducationOld struct {
		IDEscolaridade     int    `csv:"id_escolaridade"`      // Corrected to match the CSV header "id_escolaridade"
		IDUsuario          int    `csv:"id_usuario"`           // Corrected to match the CSV header "id_usuario"
		CdGrauEscolaridade int    `csv:"cd_grau_escolaridade"` // Corrected to match the CSV header "cd_grau_escolaridade"
		IDAreaEstudo       int    `csv:"id_area_estudo"`       // Corrected to match the CSV header "id_area_estudo"
		DSEspecializacao   string `csv:"ds_especializacao"`    // Corrected to match the CSV header "ds_especializacao"
		NMInstituicao      string `csv:"nm_instituicao"`       // Corrected to match the CSV header "nm_instituicao"
		DTInicio           string `csv:"dt_inicio"`            // Corrected to match the CSV header "dt_inicio"
		DTConclusao        string `csv:"dt_conclusao"`         // Corrected to match the CSV header "dt_conclusao"
	}
	Education struct {
		IDEscolaridade       int    `csv:"id_escolaridade"`
		CandidateId          int    `csv:"candidate_id"`
		EducationLevelId     int    `csv:"education_level_id"`
		AcademicDisciplineId int    `csv:"academic_discipline_id"`
		Specialization       string `csv:"specialization"`
		Institution          string `csv:"institution"`
		DateStart            string `csv:"date_start"`
		DateEnd              string `csv:"date_end"`
	}
)

func ExecEducation(wg *sync.WaitGroup) {
	defer wg.Done()
	records := extractEducationOld()
	createEducationCsv(records)
}

func extractEducationOld() []EducationOld {
	fmt.Println(Yellow + "Extracting education" + Reset)
	csvFile, err := os.Open("files/TB_SOPA_BC_ESCOLARIDADE.csv")
	if err != nil {
		panic(err)
	}
	defer csvFile.Close()

	// Create a new CSV reader with tab as the delimiter
	reader := csv.NewReader(csvFile)
	reader.Comma = ',' // Set the delimiter to tab

	var records []EducationOld
	if err := gocsv.UnmarshalCSV(reader, &records); err != nil {
		panic(err)
	}
	if len(records) == 0 {
		panic("No records found")
	}

	return records
}

func createEducationCsv(records []EducationOld) {
	file, err := os.Create(filepath.Join(basePath, "educations.csv"))
	if err != nil {
		fmt.Println(Red + err.Error() + Reset)
		panic(err)
	}
	defer file.Close()

	var educations []*Education
	for _, record := range records {
		education := &Education{
			IDEscolaridade:       record.IDEscolaridade,
			CandidateId:          record.IDUsuario,
			EducationLevelId:     record.CdGrauEscolaridade,
			AcademicDisciplineId: record.IDAreaEstudo,
			Specialization:       record.DSEspecializacao,
			Institution:          record.NMInstituicao,
			DateStart:            record.DTInicio,
			DateEnd:              record.DTConclusao,
		}
		educations = append(educations, education)
	}

	gocsv.SetCSVWriter(func(out io.Writer) *gocsv.SafeCSVWriter {
		writer := csv.NewWriter(out)
		writer.Comma = '\t'
		return gocsv.NewSafeCSVWriter(writer)
	})

	err = gocsv.MarshalFile(&educations, file)
	if err != nil {
		fmt.Println(Red + err.Error() + Reset)
		panic(err)
	}

	fmt.Println(Green + "Successfully created CSV file with the processed education." + Reset)
}
