package Friends

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"time"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
)

// CreateFriendRequest creates a FriendRequest from post data
func CreateFriendRequest(w http.ResponseWriter, r *http.Request) {
	var (
		friendRequest Models.FriendRequest
		requestBody   []byte
		returnJSON    []byte
		err           error
	)

	requestBody, err = ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	err = json.Unmarshal(requestBody, &friendRequest)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	friendRequest.AcceptedAt.Scan(nil)

	err = Database.CreateFriendRequest(&friendRequest)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	returnJSON, err = json.MarshalIndent(friendRequest, "", "  ")
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
	w.Write(returnJSON)
}

// CreateFriendRequestQrCode creates a FriendRequest from post data from qr code scan
func CreateFriendRequestQrCode(w http.ResponseWriter, r *http.Request) {
	var (
		friendRequests []Models.FriendRequest
		requestBody    []byte
		i              int
		err            error
	)

	requestBody, err = ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	err = json.Unmarshal(requestBody, &friendRequests)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	for i = range friendRequests {
		friendRequests[i].AcceptedAt.Time = time.Now()
		friendRequests[i].AcceptedAt.Valid = true
	}

	err = Database.CreateFriendRequests(&friendRequests)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
}
