package cn.quant.baa.pay.acquirer;

import cn.quant.spring.ExistsException;
import cn.quant.spring.util.StringUtils;
import com.google.common.base.Supplier;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import com.google.common.collect.Tables;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Created by Administrator on 2021/8/22 0022.
 */
public class AcquirerPropertiesSource {

    private Table<String, String, Collection<AcquirerProperties>> bigTable = Tables.newCustomTable(Maps.newHashMap()
            , new Supplier() {
                public Map<String, Collection<AcquirerProperties>> get() {
                    return Maps.newLinkedHashMap();
                }
            });

    private Map<Long, AcquirerProperties> map = new HashMap<>();

    void add(AcquirerProperties profile) {
        if (map.containsKey(profile.getMchChanId())) {
            throw new ExistsException(StringUtils.format("Existing merchant acquirer {}.", profile.getMchChanId()));
        }
        map.put(profile.getMchChanId(), profile);

        String appId = profile.getPayAppId();
        String chanCode = profile.getPayChanCode();
        Collection<AcquirerProperties> profiles = bigTable.get(appId, chanCode);
        if (profiles == null) {
            profiles = new LinkedList<>();
            bigTable.put(appId, chanCode, profiles);
        }
        profiles.add(profile);
    }

    public Map<String, Collection<AcquirerProperties>> get(String mchId, String channel) {
        Collection<AcquirerProperties> profiles = bigTable.get(mchId, channel);
        return toMap(profiles);
    }

    public Map<String, Collection<AcquirerProperties>> get(String mchId) {
        return bigTable.row(mchId);
    }

    public Map<String, Collection<AcquirerProperties>> toMap(Collection<AcquirerProperties> profiles) {
        Map<String, Collection<AcquirerProperties>> map = new HashMap<>();
        for (AcquirerProperties profile : profiles) {
            Collection<AcquirerProperties> collection = map.get(profile.getPayChanCode());
            if (collection == null) {
                collection = new LinkedList<>();
                map.put(profile.getPayChanCode(), collection);
            }
            collection.add(profile);
        }
        return map;
    }

    public AcquirerProperties get(Long channelId) {
        return map.get(channelId);
    }

    public Collection<AcquirerProperties> getAll() {
        return map.values();
    }
};