// Package corebind 的契约类型转换：在 meshray-contract 与 meshray/core 内部类型间双向转换。
package corebind

import (
	"git.zkcoi.com/zkcoi/meshray-contract"
	"git.zkcoi.com/zkcoi/meshray/core/connect"
	"git.zkcoi.com/zkcoi/meshray/core/engine"
)

// 以下函数完成开源契约类型（contract 包）与 meshray/core 内部类型之间的双向转换。
// 数值型 Layer 在 contract 与 connect 中定义一致，可直接转型。

func toCoreCandidates(in []contract.Candidate) []core.Candidate {
	out := make([]core.Candidate, 0, len(in))
	for _, c := range in {
		out = append(out, core.Candidate{
			Addr:     c.Addr,
			Type:     c.Type,
			Priority: c.Priority,
			Protocol: c.Protocol,
		})
	}
	return out
}

func toCoreICEConfig(in contract.ICEConfig) connect.ICEConfig {
	turn := make([]connect.TURNServerConfig, 0, len(in.TURNServers))
	for _, s := range in.TURNServers {
		turn = append(turn, connect.TURNServerConfig{URLs: []string{s}})
	}
	return connect.ICEConfig{
		STUNServers: in.STUNServers,
		TURNServers: turn,
	}
}

func toCoreLayerOrder(in []contract.Layer) []connect.Layer {
	out := make([]connect.Layer, 0, len(in))
	for _, l := range in {
		out = append(out, connect.Layer(l))
	}
	return out
}

func toContractStatus(in *core.EngineStatus) *contract.EngineStatus {
	if in == nil {
		return nil
	}
	peers := make(map[string]*contract.PeerStatus, len(in.Peers))
	for k, v := range in.Peers {
		peers[k] = &contract.PeerStatus{
			PeerKey:   v.PeerKey,
			Connected: v.Connected,
			Layer:     v.Layer,
		}
	}
	return &contract.EngineStatus{
		PeerCount:         in.PeerCount,
		Peers:             peers,
		ActiveConnections: in.ActiveConnections,
		TotalConnections:  in.TotalConnections,
		BytesSent:         in.BytesSent,
		BytesReceived:     in.BytesReceived,
		StrategyFallbacks: in.StrategyFallbacks,
		LastSwitchTime:    in.LastSwitchTime,
	}
}
