package network

import (
	"database/sql"
	"io/ioutil"
	"net/http"
	"strconv"

	"notabug.org/apiote/gott"
)

type Request struct {
	Id         string
	Etag       string
	Language   string
	Subid      string
	Connection *sql.DB
}

type Result struct {
	Client   *http.Client
	Request  *http.Request
	Response *http.Response
	Body     []byte
	Etag     string
	Result   interface{}
}

type HttpError struct {
	Status int
}

func (e HttpError) Error() string {
	return strconv.FormatInt(int64(e.Status), 10)
}

func AddHeaders(args ...interface{}) interface{} {
	request := args[0].(*Request)
	result := args[1].(*Result)
	result.Request.Header.Add("If-None-Match", request.Etag)
	return gott.Tuple(args)
}

func DoRequest(args ...interface{}) (interface{}, error) {
	result := args[1].(*Result)
	resp, err := result.Client.Do(result.Request)
	if err == nil && resp.StatusCode != 304 {
		result.Response = resp
	}
	return gott.Tuple(args), err
}

func HandleRequestError(args ...interface{}) (interface{}, error) {
	result := args[1].(*Result)
	if result.Response != nil && result.Response.StatusCode != 200 {
		return gott.Tuple(args), HttpError{result.Response.StatusCode}
	}
	return gott.Tuple(args), nil
}

func ReadResponse(args ...interface{}) (interface{}, error) {
	result := args[1].(*Result)
	if result.Response != nil {
		defer result.Response.Body.Close()
		body, err := ioutil.ReadAll(result.Response.Body)
		result.Body = body
		result.Etag = result.Response.Header.Get("Etag")
		return gott.Tuple(args), err
	}
	return gott.Tuple(args), nil
}
