package icsnet

import (
	"fmt"
	"net"

	"gitlab.com/cinnamon/voiceagent/icserror"
)

type IcsNeter interface {
	Listen() *icserror.IcsError

	Connect() *icserror.IcsError
	Close() *icserror.IcsError

	Write(b []byte) (int, *icserror.IcsError)
	Read(size int) ([]byte, int, *icserror.IcsError)

	LocalAddr() net.Addr
}

type IcsConn struct {
	ICSUDPConn *net.UDPConn
	ICSTCPConn *net.TCPConn
}

func GetMyIP() (string, *icserror.IcsError) {
	var retIP string
	ifaces, err := net.Interfaces()
	if err != nil {
		icserror.ICSERRNETNotFoundIF.SetError(err)
		return "", icserror.ICSERRNETNotFoundIF
	}

	for _, i := range ifaces {
		addrs, err := i.Addrs()
		// handle err
		if err != nil {
			icserror.ICSERRNETGetAddr.SetError(err)
			return "", icserror.ICSERRNETGetAddr
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			retIP = fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
		}
	}

	return retIP, nil
}
