File size: 1,504 Bytes
69f2337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from datetime import datetime
from uuid import UUID

from app.api.participants.schemas import Participant
from app.core.config import (
    PARTICIPANT_EXPECTED_PARTS,
    PARTICIPANT_PARSE_EMPTY_ERROR,
    PARTICIPANT_PARSE_INVALID_ERROR,
    PARTICIPANT_SEPARATOR,
)


class ParticipantLineParser:
    SEPARATOR = PARTICIPANT_SEPARATOR
    EXPECTED_PARTS = PARTICIPANT_EXPECTED_PARTS

    @classmethod
    def parse(cls, line: str) -> Participant:
        raw = line.strip()
        if not raw:
            raise ValueError(PARTICIPANT_PARSE_EMPTY_ERROR)

        parts = raw.split(cls.SEPARATOR)
        if len(parts) != cls.EXPECTED_PARTS:
            raise ValueError(PARTICIPANT_PARSE_INVALID_ERROR)

        participant_id, first_name, last_name, nickname, registered_at, activity_rating = parts
        return Participant(
            id=UUID(participant_id),
            first_name=first_name,
            last_name=last_name,
            nickname=nickname,
            registered_at=datetime.fromisoformat(registered_at),
            activity_rating=float(activity_rating),
        )

    @classmethod
    def serialize(cls, participant: Participant) -> str:
        return cls.SEPARATOR.join(
            [
                str(participant.id),
                participant.first_name,
                participant.last_name,
                participant.nickname,
                participant.registered_at.isoformat(),
                f"{participant.activity_rating}",
            ]
        )