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

import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iqser.red.service.persistence.management.v1.processor.entity.annotations.AnnotationEntityId;
import com.iqser.red.service.persistence.management.v1.processor.entity.annotations.ManualRedactionEntryEntity;
import com.iqser.red.service.persistence.management.v1.processor.entity.annotations.RectangleEntity;
import com.iqser.red.service.persistence.management.v1.processor.exception.NotFoundException;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.annotationentity.ManualRedactionRepository;
import com.iqser.red.service.persistence.service.v1.api.shared.model.annotations.AddRedactionRequest;
import com.iqser.red.service.persistence.service.v1.api.shared.model.annotations.AnnotationStatus;
import com.iqser.red.service.persistence.service.v1.api.shared.model.annotations.Rectangle;
import com.iqser.red.service.persistence.service.v1.api.shared.model.annotations.entitymapped.ManualRedactionEntry;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class AddRedactionPersistenceService {

    private final ManualRedactionRepository manualRedactionRepository;


    public ManualRedactionEntryEntity insert(String fileId, String annotationId, AddRedactionRequest addRedactionRequest) {

        ManualRedactionEntryEntity manualRedactionEntry = new ManualRedactionEntryEntity();
        manualRedactionEntry.setId(new AnnotationEntityId(annotationId, fileId));
        BeanUtils.copyProperties(addRedactionRequest, manualRedactionEntry);
        manualRedactionEntry.setRequestDate(OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS));
        manualRedactionEntry.setPositions(convert(addRedactionRequest.getPositions()));
        manualRedactionEntry.setTypeId(addRedactionRequest.getDossierTemplateTypeId());
        manualRedactionEntry.setDictionaryEntryType(addRedactionRequest.getDictionaryEntryType());

        if (addRedactionRequest.getStatus() == AnnotationStatus.APPROVED && !(addRedactionRequest.isAddToDictionary())) {
            manualRedactionEntry.setProcessedDate(OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS));
        }

        return manualRedactionRepository.saveAndFlush(manualRedactionEntry);

    }


    private List<RectangleEntity> convert(List<Rectangle> positions) {

        List<RectangleEntity> rectangleEntities = new ArrayList<>();
        positions.forEach(p -> {
            RectangleEntity re = new RectangleEntity();
            BeanUtils.copyProperties(p, re);
            rectangleEntities.add(re);
        });
        return rectangleEntities;
    }



    public ManualRedactionEntryEntity findAddRedaction(String fileId, String annotationId) {

        return manualRedactionRepository.findAddRedaction(new AnnotationEntityId(annotationId, fileId))
                .orElseThrow(() -> new NotFoundException("Unknown file/annotation combination: " + fileId + "/" + annotationId));
    }





    public List<ManualRedactionEntryEntity> findAddRedactions(String fileId, boolean includeDeletions) {

        return manualRedactionRepository.findByFileIdIncludeDeletions(fileId, includeDeletions);
    }


    public List<ManualRedactionEntryEntity> findAllAddRedactions() {

        return manualRedactionRepository.findAll();
    }


    @Transactional
    public void hardDelete(String fileId, String annotationId) {

        manualRedactionRepository.deleteByIdIs(new AnnotationEntityId(annotationId, fileId));
    }


    @Transactional
    public void softDelete(String fileId, String annotationId, OffsetDateTime softDeleteTime) {

        manualRedactionRepository.updateSoftDelete(new AnnotationEntityId(annotationId, fileId), softDeleteTime);
    }


    @Transactional
    public void undelete(String fileId, String annotationId) {

        manualRedactionRepository.updateSoftDelete(new AnnotationEntityId(annotationId, fileId), null);
    }


    @Transactional
    public void updateStatus(String fileId, String annotationId, AnnotationStatus annotationStatus, OffsetDateTime processedDate) {

        manualRedactionRepository.updateStatus(new AnnotationEntityId(annotationId, fileId), annotationStatus, processedDate);
    }

    @Transactional
    public void updateStatus(String fileId,
                             String annotationId,
                             AnnotationStatus annotationStatus,
                             boolean isAddOrRemoveFromDictionary,
                             Set<String> typeIdsOfModifiedDictionaries) {

        ManualRedactionEntryEntity addRedaction = manualRedactionRepository.findById(new AnnotationEntityId(annotationId, fileId))
                .orElseThrow(() -> new NotFoundException("Unknown file/annotation combination: " + fileId + "/" + annotationId));

        addRedaction.setStatus(annotationStatus);
        addRedaction.setAddToDictionary(isAddOrRemoveFromDictionary);
        addRedaction.setTypeIdsOfModifiedDictionaries(typeIdsOfModifiedDictionaries);

        manualRedactionRepository.saveAndFlush(addRedaction);
    }



    @Transactional
    public void approveStatusForRequestedRedactionsWithSameValue(Set<String> fileIds, String value) {

        manualRedactionRepository.updateStatus(fileIds, value, AnnotationStatus.REQUESTED, AnnotationStatus.APPROVED, OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS));
    }


    @Transactional
    public void markAsProcessed(ManualRedactionEntry e) {

        manualRedactionRepository.markAsProcessed(new AnnotationEntityId(e.getAnnotationId(), e.getFileId()), OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS));
    }

}
