package com.brilliance.isc.common.register.document.common;

import com.brilliance.isc.common.register.document.IDocumentRegister;
import com.brilliance.isc.common.setmod.service.SetmodService;
import com.brilliance.isc.common.trndoc.vo.DoceotVo;
import com.brilliance.isc.common.trndoc.vo.TrndocVo;
import com.brilliance.isc.common.util.StringUtils;
import com.brilliance.mda.runtime.mda.IStream;
import com.brilliance.mda.runtime.mda.impl.StreamImpl;
import com.brilliance.mda.runtime.mda.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class SetmodDocumentRegister implements IDocumentRegister {

    @Autowired
    private SetmodService setmodService;

    @Override
    public void registerDocument(TrndocVo trndoc) {
        // If any party receives a TradeConnect message, no settlement information will
        //   be included. Thus the additional TradeConnect message  "T66" has to be created
        //   automatically.
        //   => Thus the role has to be included again into stream.
        IStream tcoRolStm = new StreamImpl();
        Streams.streamClear(tcoRolStm);
        IStream othRolStm = new StreamImpl();
        Streams.streamClear(othRolStm);
        Set<String> tcoRolSet = new HashSet<>();
        Set<String> othRolSet = new HashSet<>();
        int gridcnt = 0;
        if (trndoc.getDoceot() != null) {
            gridcnt = trndoc.getDoceot().size();
        }
        for(int i = 0; i<gridcnt; i++) {
            DoceotVo doceot = trndoc.getDoceot().get(i);
            if (StringUtils.isNotEmpty(doceot.getRole()) && !("SETSUM"+doceot.getRole()).equals(doceot.getId())) {
                if ("TRO".equals(doceot.getCortyp())) {
                    tcoRolSet.add(doceot.getRole());
                } else {
                    othRolSet.add(doceot.getRole());
                }
            }
        }
        IStream parstm = trndoc.getParstm();
        if (tcoRolSet.size() > 0) {
            tcoRolSet.forEach(role -> setmodService.setmodSetRolCorFlg(role, "S", parstm));
        }
        if (othRolSet.size() > 0) {
            othRolSet.forEach(role -> setmodService.setmodSetRolCorFlg(role, "", parstm));
        }
    }
}
