package ru.yandex.autotests.direct.web.steps;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;

import static ru.yandex.autotests.direct.web.TestEnvironment.newDbSteps;

public class CidLoginCache {
    private Map<Long, String> cidToLoginCacheMap = Collections.synchronizedMap(new HashMap<>());
    private Map<Long, Long> bidToCidCacheMap = Collections.synchronizedMap(new HashMap<>());

    public Long getCidByBid(Long bid) {
        if (!bidToCidCacheMap.containsKey(bid)) {
            Long cid = newDbSteps().useShard(newDbSteps().shardingSteps().getShardByBid(bid))
                    .bannersSteps()
                    .getBanner(bid)
                    .getCid();
            bidToCidCacheMap.put(bid, cid);
        }
        return bidToCidCacheMap.get(bid);
    }

    public String getLoginByCid(Long cid) {
        if (!cidToLoginCacheMap.containsKey(cid)) {
            newDbSteps().useShard(newDbSteps().shardingSteps().getShardByCid(cid));
            cidToLoginCacheMap.put(cid, newDbSteps().usersSteps().getUsers(
                    newDbSteps().campaignsSteps().getCampaignById(cid).getUid()
            ).getLogin());
        }
        return cidToLoginCacheMap.get(cid);
    }

    public String getLoginByBid(Long bid) {
        return getLoginByCid(getCidByBid(bid));
    }

    public void mapCidToLogin(Long cid, String login) {
        cidToLoginCacheMap.put(cid, login);
    }

    public void mapBidToCid(Long bid, Long cid) {
        bidToCidCacheMap.put(bid, cid);
    }
}
