package com.xhpc.pp.server;

import org.quickserver.net.server.ClientEventHandler;
import org.quickserver.net.server.ClientHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.pp.logic.RegisterLogic.DISCONNECTED;

@Lazy(false)
@Component
public class ChargingPileEventHandler implements ClientEventHandler {

    private static final Logger log = LoggerFactory.getLogger(ChargingPileEventHandler.class);

    public ChargingPileEventHandler() {

    }

    //桩连接socket
    @Override
    public void gotConnected(ClientHandler handler) {

        String pileNo = ChargingPileServer.getPileNo(handler);
        log.debug("-> [{}] -得到连接gotConnected- {} <-", handler.getName(), handler.getSocket().getRemoteSocketAddress().toString());
        log.debug("-> ({})----[{}] -得到连接socket- {} <-", pileNo,handler.getName(), handler.getSocket().toString());
    }

    //桩断开连接socket
    @Override
    public void lostConnection(ClientHandler handler) {
        System.out.println("======pileNo==lostConnection============"+handler.toString());
        String pileNo = ChargingPileServer.getPileNo(handler);
        System.out.println("======pileNo==socket============"+pileNo);
        if (pileNo != null) {
            ChargingPileServer.disconnPileNGuns(pileNo);
            log.debug("<- ({}) -disconn关闭连接- [{}] - {} ->", pileNo, handler.getName(), handler.getSocket().getRemoteSocketAddress().toString());
            log.debug("-> [{}] -disconn关闭连接socket- {} <-", handler.getName(), handler.getSocket().toString());
        }
    }

    @Override
    public void closingConnection(ClientHandler handler) {

        String pileNo = ChargingPileServer.getPileNo(handler);
        ChargingPileServer.removeHandler(pileNo);
        String pkey = "pile:".concat(pileNo);
        Map<String, Object> cachePile = REDIS.getCacheMap(pkey);
        cachePile.put("status", DISCONNECTED);
        REDIS.setCacheMap(pkey, cachePile);
        handler.closeConnection();
        log.debug("<- ({}) -closingConnection- [{}] - {} ->", pileNo, handler.getName(), handler.getSocket().getRemoteSocketAddress().toString());
        log.debug("-> [{}] -closingConnection Socket- {} <-", handler.getName(), handler.getSocket().toString());
    }

}
