//
//  Session.swift
//  sdlan
//  Session是增加了有效时间的
//  Created by 安礼成 on 2025/7/14.
//
import Foundation
import NIOCore
import Darwin

struct Session {
    // 在内部的通讯的ip地址, 整数格式
    let dstMac: Data
    // 对端的主机在nat上映射的端口信息
    let natAddress: SocketAddress
    
    // 最后使用时间
    var lastTimestamp: Int32
    
    init(dstMac: Data, natAddress: SocketAddress) {
        self.dstMac = dstMac
        self.natAddress = natAddress
        self.lastTimestamp = Int32(Date().timeIntervalSince1970)
    }
    
    mutating func updateLastTimestamp(_ lastTimestamp: Int32) {
        self.lastTimestamp = lastTimestamp
    }
}

actor SessionManager {
    private var sessions: [Data:Session] = [:]
    
    // session的有效时间
    private let ttl: Int32 = 10
    
    func getSession(toAddress: Data) -> Session? {
        let timestamp = Int32(Date().timeIntervalSince1970)
        if var session = self.sessions[toAddress] {
            if session.lastTimestamp >= timestamp + ttl {
                session.updateLastTimestamp(timestamp)
                self.sessions[toAddress] = session
                
                return session
            } else {
                self.sessions.removeValue(forKey: toAddress)
            }
        }
        return nil
    }
    
    func addSession(session: Session) {
        self.sessions[session.dstMac] = session
    }
    
    func removeSession(dstMac: Data) {
        self.sessions.removeValue(forKey: dstMac)
    }
    
}
