package com.iqser.red.service.persistence.management.v1.processor.migration.migrations;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.entity.configuration.BaseDictionaryEntry;
import com.iqser.red.service.persistence.management.v1.processor.entity.configuration.TypeEntity;
import com.iqser.red.service.persistence.management.v1.processor.migration.Migration;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DictionaryPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.EntryPersistenceService;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.type.DictionaryEntryType;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
@Service
public class EntityTypesMigration4 extends Migration {

    private static final String NAME = "Set flags systemManaged, autoHideSkipped and hasDictionary for all entity types";
    private static final long VERSION = 4;

    @Autowired
    private DictionaryPersistenceService dictionaryPersistenceService;

    @Autowired
    private EntryPersistenceService entryPersistenceService;


    public EntityTypesMigration4() {

        super(NAME, VERSION);
    }


    @Override
    protected void migrate() {

        Set<String> systemManagedTypes = Set.of("ocr", "image", "logo", "signature", "formula", "imported_redaction", "dossier_redaction");
        Set<String> autoHideSkippedTypes = Set.of("imported_redaction");

        log.info("Will check all type entities and set systemManaged flag true for {}", systemManagedTypes);
        log.info("Will check all type entities and set autoHideSkipped flag true for {}", autoHideSkippedTypes);
        log.info("Will check all type entities and set hasDictionary flag true for types with entities");

        List<TypeEntity> types = dictionaryPersistenceService.getAllTypes(false);

        for (TypeEntity type : types) {
            if (type != null) {

                // Check if type is systemManaged
                type.setSystemManaged(type.getType() != null && systemManagedTypes.contains(type.getType()));

                // Check if type is autoHideSkipped
                type.setAutoHideSkipped(type.getType() != null && autoHideSkippedTypes.contains(type.getType()));

                // Check if type has dictionaries
                List<? extends BaseDictionaryEntry> entries = entryPersistenceService.getEntries(type.getId(), DictionaryEntryType.ENTRY, null);

                type.setHasDictionary(entries != null && !entries.isEmpty());

            }
        }

        log.info("Save all types");
        dictionaryPersistenceService.saveAllTypes(types);

    }

}
