package main

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/url"
)

type Responce struct {
	Status string
	Meta   string
}

type Request struct {
	URL string
}

type Client struct {
	InsecureSkipVerify bool
}

var config = tls.Config{
	InsecureSkipVerify: true,
}

var DefaultClient = &Client{}

func Fetch(args ...string) {
	DefaultPort := "1965"
	if len(args) < 2 {
		DefaultClient.Fetch(args[0], DefaultPort)
	}
	if len(args) > 2 {
		log.Fatal("too many args passed, just want URL and PORT")
	}
	if len(args) == 2 {
		DefaultClient.Fetch(args[0], args[1])
	}
}

func (c Client) Fetch(URL string, port string) {
	conn := c.connect(URL, port)
	defer conn.Close()
	c.sendRequest(conn, URL)
}

func (c Client) connect(URL string, port string) *tls.Conn {
	parsedURL, err := url.Parse(URL)
	if err != nil {
		log.Fatal(err)
	}

	conn, err := tls.Dial("tcp", parsedURL.Host+":"+port, &config)
	if err != nil {
		log.Fatalf("failed to connect: %v", err)
	}
	return conn
}

func (c Client) sendRequest(connection *tls.Conn, requestURL string) {
	CRLF := "\r\n"
	reqSize, err := connection.Write([]byte(requestURL + CRLF))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("request (%d bytes) sent...\n", reqSize)
}
