package ru.nbch.credit_tracker.service.xml.stax;


import lombok.extern.slf4j.Slf4j;
import ru.nbch.credit_tracker.entities.external_response.monitoring_report_error.MonitoringReportErrors;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

@Slf4j
public class MonitoringReportErrorsStaxtReader extends BaseStaxReader<MonitoringReportErrors> {

    @Override
    public Class<MonitoringReportErrors> type() {
        return MonitoringReportErrors.class;
    }

    @Override
    protected MonitoringReportErrors createObject() {
        return new MonitoringReportErrors();
    }

    @Override
    protected boolean innerProcess(XMLStreamReader reader, MonitoringReportErrors obj) throws XMLStreamException {
        String text = buffer.toString();
        String currPath = getPath();
        switch (currPath) {
            case "/Errors/Id" ->
                    obj.setId(text);
            case "/Errors/Version" ->
                    obj.setVersion(text);
            case "/Errors/User" ->
                    obj.setUser(text);
            case "/Errors/ReportCreated" ->
                    obj.setReportCreated(text);
            case "/Errors/p" -> {
                    obj.getCurrentPerson().setValue(text);
                    obj.finalizePerson();
            }
        }
        return false;
    }

    @Override
    protected void innerProcessStartElement(XMLStreamReader reader, MonitoringReportErrors obj) throws XMLStreamException {
        String currPath = getPath();

        switch (currPath) {
            case "/Errors/p" ->
                    obj.createCurrentPerson();
        }

        for (int i = 0; i < reader.getAttributeCount(); i++) {
            String text = reader.getAttributeValue(i);
            switch (reader.getAttributeLocalName(i)) {
                case "uid" -> {
                    try {
                        int uid = Integer.parseInt(text);
                        obj.getCurrentPerson().setUid(uid);
                    } catch (NumberFormatException e) {
                        log.error("Couldn't parse uid: {}", text);
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
