package com.pwt.netty.handler;

import com.pwt.netty.common.charger.ResponseMessage;
import io.netty.channel.ChannelPromise;

import java.util.AbstractMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用于连接充电机请求与响应
 */
public class ChargerPromiseHolder {

    private static final Map<ChargerRequestKey, AbstractMap.SimpleEntry<ChannelPromise, ResponseMessage>> PROMISE_MAP = new ConcurrentHashMap<>();

    public static void putPromise(ChargerRequestKey key, ChannelPromise promise) {
        PROMISE_MAP.put(key, new AbstractMap.SimpleEntry<ChannelPromise, ResponseMessage>(promise, null));
    }

    public static AbstractMap.SimpleEntry<ChannelPromise, ResponseMessage> getEntry(ChargerRequestKey key) {
        return PROMISE_MAP.get(key);
    }

    public static void remove(ChargerRequestKey key) {
        PROMISE_MAP.remove(key);
    }

    public static boolean completePromise(ChargerRequestKey key, ResponseMessage response) {
        if (!PROMISE_MAP.containsKey(key)) {
            return false;
        }
        AbstractMap.SimpleEntry<ChannelPromise, ResponseMessage> entry = PROMISE_MAP.get(key);
        if (entry != null) {
            ChannelPromise promise = entry.getKey();
            if (promise.isDone() || promise.isCancelled()) {
                return false;
            }
            entry.setValue(response);
            promise.setSuccess();
            return true;
        }
        return false;
    }

    public static class ChargerRequestKey {
        private final String chargerGunId;
        private final int type;
        private final long streamId;

        public ChargerRequestKey(String chargerGunId, int type, long streamId) {
            this.chargerGunId = chargerGunId;
            this.type = type;
            this.streamId = streamId;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            ChargerRequestKey that = (ChargerRequestKey) o;
            return type == that.type && streamId == that.streamId && chargerGunId.equals(that.chargerGunId);
        }

        @Override
        public int hashCode() {
            return Objects.hash(chargerGunId, type, streamId);
        }
    }

    private ChargerPromiseHolder() {
    }
}
