package http_wrapper

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

type Option func(*Client) error

func TimeoutOption(timeout time.Duration) Option {
	return func(c *Client) error {
		c.Client.Timeout = timeout
		return nil
	}
}

func MaxIdleConnOption(connCount int) Option {
	return func(c *Client) error {
		// todo: is there better way to update transport
		// get the old transport and replace by new one
		oldTransport := c.Transport
		oldTransportPointer, ok := oldTransport.(*http.Transport)
		if !ok {
			return fmt.Errorf("transport not an *http.Transport")
		}
		// create new transport
		newTransport := &http.Transport{
			Proxy:                 oldTransportPointer.Proxy,
			DialContext:           oldTransportPointer.DialContext,
			MaxIdleConns:          connCount,
			MaxIdleConnsPerHost:   connCount,
			IdleConnTimeout:       oldTransportPointer.IdleConnTimeout,
			TLSHandshakeTimeout:   oldTransportPointer.TLSHandshakeTimeout,
			ExpectContinueTimeout: oldTransportPointer.ExpectContinueTimeout,
			// todo: set tls config
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		c.Transport = newTransport
		return nil
	}
}

func TransportOption(rt http.RoundTripper) Option {
	return func(c *Client) error {
		c.Transport = rt
		return nil
	}
}
