package auth

import (
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"strconv"

	"../../../config"
	"../curl"
)

type UserData struct {
	UserId   string     `json:"id_user"`
	Email    string     `json:"email"`
	Name     string     `json:"name"`
	Username string     `json:"username"`
	Token    string     `json:"token"`
	UrlToken string     `json:"url_token"`
	Avatar   string     `json:"avatar"`
	Language string     `json:"language"`
	Errors   []apiError `json:"errors"`
}

type apiError struct {
	Type      string `json:"type"`
	Parameter string `json:"parameter"`
	Message   string `json:"message"`
}

func (user UserData) getId() int {
	id, _ := strconv.Atoi(user.UserId)
	return id
}

func GetUser(httpReq *http.Request) (*UserData, bool) {

	curlReq, err := curlRequest(httpReq)

	if err != nil {
		return nil, false
	}

	response, err := curl.Curl(curlReq)

	if err != nil {
		log.Print(err)
		return nil, false
	}

	var userData UserData

	err = json.Unmarshal(response, &userData)

	//fmt.Printf("%+v\n", userData)

	if err != nil {
		log.Print(err)
		return nil, false
	}

	if len(userData.Errors) > 0 {
		return nil, false
	}

	return &userData, true
}

func curlRequest(request *http.Request) (*curl.Request, error) {

	authToken := request.Header.Get("Auth")

	if authToken != "" {

		headers := make(map[string]string)

		headers["Auth"] = authToken

		curlReq := &curl.Request{
			Url:     config.AUTHENTICATION_SERVICE,
			Method:  "POST",
			Headers: headers,
		}

		return curlReq, nil
	}

	return nil, errors.New("No auth token found in http request")
}
