package com.iqser.red.service.persistence.management.v1.processor.service.redactionlog;

import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.service.v1.api.shared.model.redactionlog.RedactionLogEntry;
import com.iqser.red.service.persistence.service.v1.api.shared.model.redactionlog.section.SectionGrid;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SectionTextService {

    public void handleSectionText(SectionGrid sectionGrid, RedactionLogEntry redactionLogEntry) {

        if (redactionLogEntry.getSection() != null) {
            // set by UI
            return;
        }

        if (sectionGrid != null) {
            var firstPosition = !redactionLogEntry.getPositions().isEmpty() ? redactionLogEntry.getPositions().iterator().next() : null;

            if (firstPosition != null) {

                for (var section : sectionGrid.getSections()) {
                    if (section.getPages().contains(firstPosition.getPage())) {
                        for (var sectionArea : section.getSectionAreas()) {
                            if (sectionArea.contains(firstPosition)) {
                                redactionLogEntry.setSection(section.getHeadline());
                                redactionLogEntry.setSectionNumber(section.getSectionNumber());
                                return;
                            }
                        }
                    }
                }
            }
        }
    }

}
