package main

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

	"github.com/gocarina/gocsv"
)

type (
	CoursesOld struct {
		IDCurso       int    `csv:"id_curso"`
		IDUsuario     int    `csv:"id_usuario"`
		NMCurso       string `csv:"nm_curso"`
		NMInstituicao string `csv:"nm_instituicao"`
		DSDuracao     string `csv:"ds_duracao"`
		DTConclusao   string `csv:"dt_conclusao"`
	}
	Courses struct {
		ID          int    `csv:"id"`
		CandidateID int    `csv:"candidate_id"`
		Name        string `csv:"name"`
		Institution string `csv:"institution"`
		Duration    string `csv:"duration"`
		DateEnd     string `csv:"date_end"`
	}
)

func ExecCourses(wg *sync.WaitGroup) {
	defer wg.Done()
	records := extractCoursesOld()
	createCoursesCsv(records)
}

func extractCoursesOld() []CoursesOld {
	fmt.Println(Yellow + "Extracting courses" + Reset)
	csvFile, err := os.Open("files/TB_SOPA_BC_CURSO.csv")
	if err != nil {
		fmt.Println(Red + err.Error() + Reset)
		panic(err)
	}
	defer csvFile.Close()

	reader := csv.NewReader(csvFile)
	reader.Comma = ',' // Set the delimiter to tab

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

	return records
}

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

	var courses []*Courses
	for _, record := range records {
		// cleanedName := strings.ReplaceAll(record.NMCurso, "\u2022", "")
		cleanedName := replaceCharacter("\u2022", "", record.NMCurso)
		cleanedName = strings.TrimSpace(cleanedName)
		course := &Courses{
			ID:          record.IDCurso,
			CandidateID: record.IDUsuario,
			Name:        cleanedName,
			Institution: record.NMInstituicao,
			Duration:    record.DSDuracao,
			DateEnd:     record.DTConclusao,
		}
		courses = append(courses, course)
	}

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

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

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