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

import java.util.List;

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

import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.DossierTemplateEntity;
import com.iqser.red.service.persistence.management.v1.processor.migration.Migration;
import com.iqser.red.service.persistence.management.v1.processor.service.DefaultDateFormatsProvider;
import com.iqser.red.service.persistence.management.v1.processor.service.CurrentApplicationTypeProvider;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DateFormatsPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DossierTemplatePersistenceService;

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

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

    private static final String NAME = "Migration for adding date formats files to dossier templates";
    private static final long VERSION = 25;

    @Autowired
    private DateFormatsPersistenceService dateFormatsPersistenceService;
    @Autowired
    private DossierTemplatePersistenceService dossierTemplatePersistenceService;
    @Autowired
    private DefaultDateFormatsProvider defaultDateFormatsProvider;
    @Autowired
    private CurrentApplicationTypeProvider currentApplicationTypeProvider;


    public V25AddDateFormatsToTemplatesMigration() {

        super(NAME, VERSION);
    }


    @Override
    @SneakyThrows
    protected void migrate() {

        if (!currentApplicationTypeProvider.isDocuMine()) {
            log.info("Skipping AddDateFormatsToTemplatesMigration25 as application type is not DocuMine!!!");
            return;
        }

        List<DossierTemplateEntity> allDossierTemplates = dossierTemplatePersistenceService.getAllDossierTemplates();
        allDossierTemplates.forEach(dt -> {
            try {
                dateFormatsPersistenceService.setDateFormats(defaultDateFormatsProvider.getDateFormats(), dt.getId(), -1);
            } catch (Exception e) {
                log.info("Could not update dossier template {}, error: {}", dt.getId(), e.getMessage());
            }
        });

    }

}
