package com.imdroid.sideslope.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;
import lombok.Data;

import java.net.InetSocketAddress;

/**
 * @author Layton
 * @date 2023/2/2 21:00
 */
@Data
public class DeviceChannel {
    private String deviceId;
    private String imei;

    private Channel channel;

    private InetSocketAddress address;

    private long lastTime;

    private boolean tcp;

    public DeviceChannel(String deviceId, Channel channel, InetSocketAddress address) {
        this.deviceId = deviceId;
        this.channel = channel;
        this.address = address;
        lastTime = System.currentTimeMillis();
        this.tcp = (address == null);
    }

    public boolean isOnline() {
        if (tcp) {
            return channel.isActive();
        }
//        return (System.currentTimeMillis() - lastTime) < 28 * 1000L;
        return true;
    }

    public void writeAndFlush(ByteBuf buf) {
        if (tcp) {
            channel.writeAndFlush(buf);
        } else {
            channel.writeAndFlush(new DatagramPacket(buf, address));
        }
    }
}
