package src

import (
	"context"
	"fmt"

	"encoding/base64"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"golang.org/x/crypto/blake2s"
)

const uri = "mongodb://192.168.0.159:27017"
const salt = "ENVIRONMENT"

var dbCollection *mongo.Collection
var dbDevices *mongo.Collection
var mongoClient *mongo.Client

func DbConnect() {
	mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))

	if err != nil {
		panic(err)
	}

	if err := mongoClient.Ping(context.TODO(), readpref.Primary()); err != nil {
		panic(err)
	}
	db := mongoClient.Database("Environment")
	dbCollection = db.Collection("Main")
	dbDevices = db.Collection("Devices")
}

func GetDeviceKey(api uint64) ([]byte, error) {
	apiSigned := int64(api)
	filter := bson.D{{"ApiID", apiSigned}}
	var result bson.M
	err := dbDevices.FindOne(context.TODO(), filter).Decode(&result)
	if err != nil {
		return nil, err
	}

	key, err := DeriveKey(result["Passcode"].(string))
	fmt.Printf(base64.StdEncoding.EncodeToString(key))
	// We should cache this!
	return key, err
}

func DeriveKey(passcode string) ([]byte, error) {

	hash, err := blake2s.New256(nil)
	if err != nil {
		return nil, err
	}
	hash.Write([]byte(salt))
	hash.Write([]byte(passcode))

	fmt.Printf("SALT %s PASS %s\n", salt, passcode)

	return hash.Sum(nil), nil
}

func DbDisconnect() {
	err := mongoClient.Disconnect(context.TODO())
	if err != nil {
		panic(err)
	}
}
