package service

import (
	"crypto/tls"
	"net"
	"time"
)

type ConnFactory interface {
	createSocket(ip string, port string) (net.Conn, error)
	Type() string
}

type ConnFactoryNormal struct {
	t string
}

func (n ConnFactoryNormal) Type() string {
	return n.t
}

func (n ConnFactoryNormal) createSocket(ip string, port string) (net.Conn, error) {
	netinfo := ip + ":" + port
	conn, err := net.DialTimeout("tcp", netinfo, time.Duration(3)*time.Second)
	if err != nil {
		return nil, err
	}

	err = conn.SetDeadline(time.Now().Add(3 * time.Second))
	if err != nil {
		return nil, err
	}
	return conn, err
}

type ConnFactoryTLS struct {
	t string
}

func (n ConnFactoryTLS) Type() string {
	return n.t
}

func (n ConnFactoryTLS) createSocket(ip string, port string) (net.Conn, error) {
	netinfo := ip + ":" + port
	dialer := &net.Dialer{
		Timeout: 3 * time.Second,
	}
	conn, err := tls.DialWithDialer(
		dialer,
		"tcp",
		netinfo,
		&tls.Config{
			InsecureSkipVerify: true,
			ServerName:         ip,
		},
	)
	if err != nil {
		return nil, err
	}

	err = conn.SetDeadline(time.Now().Add(3 * time.Second))
	if err != nil {
		return nil, err
	}
	return conn, err
}
