package SunnyProxy

import (
	"Sunny/src/net/http"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"strconv"
	"strings"
)

type Entity struct {
	Request      *http.Request
	Response     *http.Response
	Ip           string
	Auth         string
	ProxyTimeout int
	Pid          string
	ClientIp     []byte
}

func NewEntityWithRequest(request *http.Request, ip []byte) (*Entity, error) {
	var bodyBytes = []byte{}
	var err error
	if request.Method == "GET" {
	} else {
		if request.Body == nil {
			request.Body = ioutil.NopCloser(bytes.NewBuffer(make([]byte, 0)))
		}

		bodyBytes, err = ioutil.ReadAll(request.Body)
		if err != nil {
			return nil, err
		}

		request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
	}

	return &Entity{
		Request:  request,
		ClientIp: ip,
	}, nil
}

func (entity *Entity) ReadAll(r io.Reader) ([]byte, error) {
	var bufBuffer bytes.Buffer
	b := make([]byte, 4096)
	defer func() {
		b = make([]byte, 0)
		bufBuffer.Reset()
		bufBuffer.Grow(0)

	}()
	for {
		n, err := r.Read(b[0:])
		bufBuffer.Write(b[0:n])
		if err != nil {
			if err == io.EOF {
				err = nil
			}
			return bufBuffer.Bytes(), err
		}
	}
}

func (entity *Entity) SetResponse(response *http.Response, w net.Conn, NoticeTheRecuesZ bool) error {
	if NoticeTheRecuesZ {
		text := response.Status
		if text == "" {
			text = "status code " + strconv.Itoa(response.StatusCode)
		} else {
			text = strings.TrimPrefix(text, strconv.Itoa(response.StatusCode)+" ")
		}
		text = fmt.Sprintf("HTTP/%d.%d %03d %s\r\n", response.ProtoMajor, response.ProtoMinor, response.StatusCode, text)
		w.Write([]byte(text))
		for name, values := range response.Header {
			for _, value := range values {
				w.Write([]byte(name + ": " + value + "\r\n"))
			}
		}
		w.Write([]byte("\r\n"))
		io.Copy(w, response.Body)
		response.Body.Close()
		//fmt.Println(entity.ReadAll2(response, w))
		return nil
	}

	bodyBytes, err := entity.ReadAll(response.Body)
	if response.Body != nil {
		_ = response.Body.Close()
	}

	if err != nil {
		return err
	}

	response.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

	return nil
}

func (entity *Entity) SetScheme(scheme string) {
	entity.Request.URL.Scheme = scheme
}

func (entity *Entity) SetHost(host string) {
	entity.Request.URL.Host = host
}

func (entity *Entity) SetRemoteAddr(remoteAddr string) {
	entity.Request.RemoteAddr = remoteAddr
}
