package Seeder

import (
	"encoding/base64"
	"io"
	"os"
	"time"

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

func seedFriend(userRequestTo, userRequestFrom Models.User, accepted bool) error {
	var (
		friendRequest Models.FriendRequest
		symKey        AesKey
		encPublicKey  []byte
		err           error
	)

	symKey, err = GenerateAesKey()
	if err != nil {
		return err
	}

	encPublicKey, err = symKey.AesEncrypt([]byte(PublicKey))
	if err != nil {
		return err
	}

	friendRequest = Models.FriendRequest{
		UserID: userRequestTo.ID,
		FriendID: base64.StdEncoding.EncodeToString(
			EncryptWithPublicKey(
				[]byte(userRequestFrom.ID.String()),
				decodedPublicKey,
			),
		),
		FriendUsername: base64.StdEncoding.EncodeToString(
			EncryptWithPublicKey(
				[]byte(userRequestFrom.Username),
				decodedPublicKey,
			),
		),
		FriendPublicAsymmetricKey: base64.StdEncoding.EncodeToString(
			encPublicKey,
		),
		SymmetricKey: base64.StdEncoding.EncodeToString(
			EncryptWithPublicKey(symKey.Key, decodedPublicKey),
		),
	}

	if accepted {
		friendRequest.AcceptedAt.Time = time.Now()
		friendRequest.AcceptedAt.Valid = true
	}

	return Database.CreateFriendRequest(&friendRequest)
}

func copyProfileImage() error {
	var (
		srcFile *os.File
		dstFile *os.File
		err     error
	)

	srcFile, err = os.Open("./Database/Seeder/profile_image_enc.dat")
	if err != nil {
		return err
	}

	dstFile, err = os.Create("./attachments/profile_image")
	if err != nil {
		return err
	}

	defer dstFile.Close()
	_, err = io.Copy(dstFile, srcFile)
	return err
}

// SeedFriends creates dummy friends for testing/development
func SeedFriends() {
	var (
		primaryUser   Models.User
		secondaryUser Models.User
		accepted      bool
		i             int
		err           error
	)

	// err = copyProfileImage()
	// if err != nil {
	// 	panic(err)
	// }

	primaryUser, err = Database.GetUserByUsername("testUser")
	if err != nil {
		panic(err)
	}

	secondaryUser, err = Database.GetUserByUsername("ATestUser2")
	if err != nil {
		panic(err)
	}

	err = seedFriend(primaryUser, secondaryUser, true)
	if err != nil {
		panic(err)
	}

	err = seedFriend(secondaryUser, primaryUser, true)
	if err != nil {
		panic(err)
	}

	accepted = false

	for i = 0; i <= 5; i++ {
		secondaryUser, err = Database.GetUserByUsername(userNames[i])
		if err != nil {
			panic(err)
		}

		if i > 3 {
			accepted = true
		}

		err = seedFriend(primaryUser, secondaryUser, accepted)
		if err != nil {
			panic(err)
		}

		if accepted {
			err = seedFriend(secondaryUser, primaryUser, accepted)
			if err != nil {
				panic(err)
			}
		}
	}
}
