package de.accso.flexinale.data.services;

import de.accso.flexinale.data.model.Kino;
import de.accso.flexinale.data.model.KinoSaal;
import de.accso.flexinale.data.persistence.AbstractDao;
import de.accso.flexinale.data.persistence.KinoSaalDao;
import de.accso.flexinale.shared_kernel.FlexinaleIllegalArgumentException;
import jakarta.transaction.Transactional;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

@Service
@Transactional
public non-sealed class KinoSaalUploadService extends AbstractExcelDataUploadService<KinoSaal> {
    private static final Logger LOGGER = LoggerFactory.getLogger(KinoSaalUploadService.class);

    @Autowired
    private KinoSaalDao kinoSaalDao;

    @Override
    public AbstractDao<KinoSaal> getDao() {
        return kinoSaalDao;
    }

    @Override
    public String getNameOfExcelDataType() {
        return KinoSaal.class.getSimpleName();
    }

    @Override
    public KinoSaal createDataFromExcelRow(final Row excelRow) {
        String kinoSaalId = excelRow.getCell(0).getStringCellValue();

        String kinoId = excelRow.getCell(3).getStringCellValue();

        Cell cellAnzahlPlaetze = excelRow.getCell(2);
        int anzahlPlaetze =
                switch(cellAnzahlPlaetze.getCellType()) {
                    case NUMERIC -> (int) cellAnzahlPlaetze.getNumericCellValue();
                    case STRING  -> Integer.parseInt(cellAnzahlPlaetze.getStringCellValue());
                    default -> throw new FlexinaleIllegalArgumentException("Anzahl Plaetze is not a number");
                };

        KinoSaal kinoSaal = new KinoSaal(
                kinoSaalId,
                excelRow.getCell(1).getStringCellValue(),
                anzahlPlaetze,
                new Kino(kinoId)
        );

        LOGGER.debug("New KinoSaal created: " + kinoSaal);

        return kinoSaal;
    }

    public Map<String, Collection<KinoSaal>> mapKinoSaeleToKino(final Collection<KinoSaal> kinoSaele) {
        Map<String, Collection<KinoSaal>> saeleUndKinos = new HashMap<>();
        for (KinoSaal saal : kinoSaele) {
            String key = saal.kino.id;

            Collection<KinoSaal> kinoSaeleAlreadyMapped = saeleUndKinos.get(key);
            if (kinoSaeleAlreadyMapped == null) {
                HashSet<KinoSaal> saele = new HashSet<>();
                saele.add(saal);
                saeleUndKinos.put(key, saele);
            }
            else {
                kinoSaeleAlreadyMapped.add(saal);
                saeleUndKinos.put(key, kinoSaeleAlreadyMapped);
            }
        }
        return saeleUndKinos;
    }
}
