package Friends

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

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
	"github.com/gorilla/mux"
)

// AcceptFriendRequest accepts friend requests
func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) {
	var (
		oldFriendRequest Models.FriendRequest
		newFriendRequest Models.FriendRequest
		urlVars          map[string]string
		friendRequestID  string
		requestBody      []byte
		ok               bool
		err              error
	)

	urlVars = mux.Vars(r)
	friendRequestID, ok = urlVars["requestID"]
	if !ok {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	oldFriendRequest, err = Database.GetFriendRequestByID(friendRequestID)
	if err != nil {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	oldFriendRequest.AcceptedAt.Time = time.Now()
	oldFriendRequest.AcceptedAt.Valid = true

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

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

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

	newFriendRequest.AcceptedAt.Time = time.Now()
	newFriendRequest.AcceptedAt.Valid = true

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

	w.WriteHeader(http.StatusNoContent)
}
