"""
Parse backup memory CSV file of BSM SPORTident station generated by SI Config Plus

-- Format:
CSV, separator ";"
Needed positions: card number (2), start (15), finish (21), splits (44): count of punches, (code + time) * n

No;Read on;SIID;Start no;Clear CN;Clear DOW;Clear time;Clear_r CN;Clear_r DOW;Clear_r time;Check CN;Check DOW;Check time
;Start CN;Start DOW;Start time;Start_r CN;Start_r DOW;Start_r time;Finish CN;Finish DOW;Finish time;Finish_r CN;Finish_r
DOW;Finish_r time;Class;First name;Last name;Club;Country;Email;Date of birth;Sex;Phone;Street;ZIP;City;Hardware version
;Software version;Battery date;Battery voltage;Clear count;Character set;SEL_FEEDBACK;No. of records;Record 1 CN;Record
1 DOW;Record 1 time;Record 2 CN;Record 2 DOW;Record 2 time;Record 3 CN;

-- Example:
440;2023-12-17 11:59:02;2007313;;2;Su; 12:40:50;;;;2;Su; 12:40:50;;;;;;;1;Su; 14:50:45;;;;;2007313;SPORTident Ru;;;;;;;;
;;;;;;;;;10;34;Su; 12:41:33;49;Su; 12:54:39;43;Su; 13:22:28;39;Su; 13:51:28;42;Su; 14:02:34;46;Su; 14:15:04;40;Su; 14:31
:03;47;Su; 14:39:54;37;Su; 14:47:02;90;Su; 14:49:21;

"""

import csv

from sportorg.common.otime import OTime
from sportorg.models.memory import Race, ResultSportident, Split
from sportorg.modules.sportident.fix_time_sicard_5 import fix_time
from sportorg.utils.time import hhmmss_to_time

POS_CARD = 2
POS_START = 15
POS_FINISH = 21
POS_COUNT = 44


def recovery(file_name: str, race: Race) -> None:
    separator = ';'

    zero_time_val = race.get_setting('system_zero_time', (8, 0, 0))
    zero_time = OTime(
        hour=zero_time_val[0], minute=zero_time_val[1], sec=zero_time_val[2]
    )

    with open(file_name, encoding='cp1251') as csv_file:
        spam_reader = csv.reader(csv_file, delimiter=separator)
        for tokens in spam_reader:
            if tokens[0] == 'No' or len(tokens) < 45:
                continue

            res = ResultSportident()
            res.card_number = int(tokens[POS_CARD])
            res.start_time = hhmmss_to_time(tokens[POS_START])
            res.finish_time = hhmmss_to_time(tokens[POS_FINISH])

            punch_count = int(tokens[POS_COUNT])
            existing_punches = (len(tokens) - POS_COUNT - 1) // 3

            for i in range(min(punch_count, existing_punches)):
                punch = Split()
                punch.code = tokens[POS_COUNT + 3 * i + 1]
                punch.time = hhmmss_to_time(tokens[POS_COUNT + 3 * i + 3])
                res.splits.append(punch)

            fix_time(res, zero_time)
            race.results.append(res)
