package com.its.op.global;

import com.its.op.entity.its.vms.TbVmsSymbIfsc;
import com.its.op.entity.its.vms.TbVmsSymbLib;
import com.its.op.dao.repository.its.vms.TbVmsSymbIfscRepository;
import com.its.op.dao.repository.its.vms.TbVmsSymbLibRepository;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@RequiredArgsConstructor
@Getter
@Component
public class VmsSymbLibManager {

    private final TbVmsSymbLibRepository repo;
    private final TbVmsSymbIfscRepository ifscRepo;

    private static final ConcurrentHashMap<Integer, TbVmsSymbLib> lib = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<Integer, Map<Integer, TbVmsSymbIfsc>> ifsc = new ConcurrentHashMap<>();

    @PostConstruct
    void init() {
        load();
    }

    public void load() {

        List<TbVmsSymbLib> objList = repo.findAll();
        objList.forEach(obj -> {
            lib.put(obj.getSymbLibNmbr(), obj);
        });

        List<TbVmsSymbIfsc> ifscList = ifscRepo.findAll();
        ifscList.forEach(obj -> {
            Map<Integer, TbVmsSymbIfsc> ifscMap = ifsc.get(obj.getSymbLibNmbr());
            if (ifscMap == null) {
                ifscMap = new HashMap<>();
                ifsc.put(obj.getSymbLibNmbr(), ifscMap);
            }
            ifscMap.put(obj.getCellId(), obj);
        });

        //log.info("=== {}", lib);
    }

    public static TbVmsSymbLib get(Integer id) {
        if (id == null) {
            return null;
        }
        return lib.get(id);
    }

    public static TbVmsSymbIfsc getIfsc(Integer id) {
        if (id == null) {
            return null;
        }
        Map<Integer, TbVmsSymbIfsc> ifscMap = ifsc.get(id);
        if (ifscMap != null) {
            return ifscMap.get(1);
        }
        return null;
    }

    public static Map<Integer, TbVmsSymbIfsc> getIfscMap(Integer id) {
        if (id == null) {
            return null;
        }
        return ifsc.get(id);
    }

}
