package com.its.dsrc.global;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.its.dsrc.entity.TbRseCtlr;
import com.its.dsrc.entity.TbRseObuNonCrypt;
import com.its.dsrc.entity.TbRseOffrDrct;
import com.its.dsrc.entity.TbRseSect;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Getter
@Setter
@Slf4j
public class AppRepository {
    private static AppRepository _instance = null;

    public ConcurrentHashMap<String, TbRseCtlr> ctlrMap = null;
    public ConcurrentHashMap<String, TbRseCtlr> ctlrIpMap = null;
    public ConcurrentHashMap<Channel, TbRseCtlr> ctlrChannelMap = null;

    // RSE_SECT 정보관리, RSE Sect 관리(sect_id, start_rsd_id, end_rse_id, ...)
    public ConcurrentHashMap<String, TbRseSect> rseSectMap = null;
    // 시작 RSE 를 키로 하는 SECT_ID 목록, { STRT_ID, [SECT_ID, SECT_ID, ...] }
    public Multimap<String, String> rseSectStartMap = null;
    // 종료 RSE 를 키로 하는 SECT_ID 목록, { END_ID, [SECT_ID, SECT_ID, ...] }
    public Multimap<String, String> rseSectEndMap = null;

    public List<TbRseObuNonCrypt> rseObuNonCryptList = null;
    public List<TbRseOffrDrct> rseOffrDrctList = null;

    public static AppRepository getInstance() {
        if (_instance == null) {
            synchronized (AppRepository.class) {
                if (_instance == null)
                    _instance = new AppRepository();
            }
        }
        return _instance;
    }

    public AppRepository() {
        this.ctlrMap = new ConcurrentHashMap<>();
        this.ctlrIpMap = new ConcurrentHashMap<>();
        this.ctlrChannelMap = new ConcurrentHashMap<>();
        this.rseSectMap = new ConcurrentHashMap<>();
        this.rseSectStartMap = Multimaps.synchronizedMultimap((Multimap)HashMultimap.create());
        this.rseSectEndMap = Multimaps.synchronizedMultimap((Multimap)HashMultimap.create());
        this.rseObuNonCryptList = Collections.synchronizedList(new ArrayList<>());
        this.rseOffrDrctList = Collections.synchronizedList(new ArrayList<>());
    }

    public List<TbRseOffrDrct> getRseOffrDrctList(String rseId) {
        List<TbRseOffrDrct> list = Collections.synchronizedList(new ArrayList<>());
        for (TbRseOffrDrct vo : this.rseOffrDrctList) {
            if (vo.getRSE_CTLR_NMBR().equals(rseId))
                list.add(vo);
        }
        return list;
    }

}
