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

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

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.repository.DossierTemplateRepository;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.TypeRepository;

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

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

    private static final String NAME = "Add Manual Redaction Type";
    private static final long VERSION = 9;
    private static final String MANUAL_TYPE = "manual";

    @Autowired
    private DictionaryPersistenceService dictionaryPersistenceService;
    @Autowired
    private DossierTemplateRepository dossierTemplateRepository;
    @Autowired
    private TypeRepository typeRepository;


    public ManualRedactionTypeMigration9() {

        super(NAME, VERSION);
    }


    @Override
    protected void migrate() {

        var allDossierTemplates = dossierTemplateRepository.findAll();

        allDossierTemplates.forEach(dossierTemplateEntity -> {

            var entitiesForDossierTemplate = dictionaryPersistenceService.getAllTypesForDossierTemplate(dossierTemplateEntity.getId(), true);

            var manualType = entitiesForDossierTemplate.stream().filter(e -> MANUAL_TYPE.equals(e.getType())).findAny();
            manualType.ifPresent(typeEntity -> typeRepository.deleteById(typeEntity.getId()));

            var rank = 1;
            for (var entity : entitiesForDossierTemplate) {
                if (entity.getRank() > rank) {
                    rank = entity.getRank();
                }
            }
            rank += 1000;

            dictionaryPersistenceService.addType(MANUAL_TYPE,
                    dossierTemplateEntity.getId(),
                    "#9398a0",
                    "#c5d3eb",
                    "#c498fa",
                    rank,
                    false,
                    false,
                    false,
                    "Manual Redactions",
                    false,
                    "Manual Redactions",
                    null,
                    false,
                    true,
                    false,
                    true);

        });

    }

}





