/*
** Job Arranger for ZABBIX
** Copyright (C) 2025 Daiwa Institute of Research Ltd. All Rights Reserved.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/
package jatcp

import (
	"context"
	"fmt"
	"net"
	"time"

	"jobarranger2/src/libs/golibs/common"
)

type TcpClient struct {
	hostname     	string
	listenPort   	int
	sourceIP 		string
	timeout 		time.Duration
}

func CreateTcpClient(hostname string, listenPort int, timeoutInSec uint, sourceIP string) *TcpClient {

	return &TcpClient{
		hostname:     	hostname,
		listenPort:   	listenPort,
		timeout: 		time.Second * time.Duration(timeoutInSec),
		sourceIP: 		sourceIP,
	}
}

func (client *TcpClient) Connect() (*common.NetConnection, error) {
	var d net.Dialer

	// set the sourceIP
	if client.sourceIP != "" {
		localAddr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(client.sourceIP, "0"))
		if err != nil {
			return nil, fmt.Errorf("failed to resolve source IP %s: %w", client.sourceIP, err)
		}
		d.LocalAddr = localAddr
	}

	address := fmt.Sprintf("%s:%d", client.hostname, client.listenPort)

	ctx, cancel := context.WithTimeout(context.Background(), client.timeout)
	defer cancel()

	conn, err := d.DialContext(ctx, "tcp", address)
	if err != nil {
		return nil, err
	}

	tcpConn, ok := conn.(*net.TCPConn)
	if !ok {
		conn.Close()
		return nil, fmt.Errorf("type cast failed from net.Conn to net.TCPConn")
	}

	tcpConn.SetNoDelay(true)
	return &common.NetConnection{
		Conn: tcpConn,
	}, nil
}
