summaryrefslogtreecommitdiff
path: root/input.go
blob: 206d99f811e06354bb0c4dfae22b0c7ec8c0dfa9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"strings"

	"github.com/jszwec/csvutil"
)

type Participant struct {
	LastName    string `csv:"lastname"`
	FirstName   string `csv:"firstname"`
	DateOfBirth string `csv:"dateofbirth"`
	Gender      Gender `csv:"gender"`
	Nation      string `csv:"nation"`
	Region      string `csv:"region"`
	ClubStr     string `csv:"club"`
	Id          uint   `csv:"-"`
	ClubId      uint   `csv:"-"`
}

type Club struct {
	Name string
	Id   uint
}

func (p Participant) MainClub() string {
	if strings.Contains(p.ClubStr, ", ") {
		return strings.Split(p.ClubStr, ", ")[0]
	}
	return p.ClubStr
}

func parseOphardtInput(fileName string) ([]Participant, []Club, error) {
	f, err := os.Open(fileName)
	if err != nil {
		return nil, nil, fmt.Errorf("opening input file '%s': %w", fileName, err)
	}

	encReader, err := encodedReader(f)
	if err != nil {
		return nil, nil, fmt.Errorf("cannot determine encoding of file '%s': %w", fileName, err)
	}

	csvReader := csv.NewReader(encReader)
	csvReader.Comma = ';'

	dec, err := csvutil.NewDecoder(csvReader)
	if err != nil {
		return nil, nil, fmt.Errorf("reading from file '%s': %w", fileName, err)
	}
	dec.DisallowMissingColumns = true

	var participants []Participant
	if err = dec.Decode(&participants); err != nil {
		return nil, nil, fmt.Errorf("decoding file '%s': %w", fileName, err)
	}

	clubs := prepareParticipants(participants)
	return participants, clubs, nil
}

func prepareParticipants(participants []Participant) []Club {
	clubMap := map[string]uint{}
	var clubs []Club
	var clubId, participantId uint

	for i := range participants {
		participantId++

		p := &participants[i]
		p.Id = participantId

		club := p.MainClub()
		if cId, ok := clubMap[club]; ok {
			p.ClubId = cId
		} else {
			clubId++

			p.ClubId = clubId
			clubMap[club] = clubId
			clubs = append(clubs, Club{club, clubId})
		}
	}

	return clubs
}