package main

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"os"

	"storj.io/uplink"
)

// Fetch all storj data here. Keys in env
type Env struct {
	accessGrant string
	bucketName  string
	objectKey   string
}

func getCapsaiBucketEnv() (env Env) {
	env = Env{
		accessGrant: os.Getenv("ACCESS_GRANT"),
		bucketName:  "capsailanding",
		objectKey:   "",
	}

	return
}

func DownloadFromBucket(ctx context.Context, env Env, data []byte) ([]byte, error) {

	// verification steps
	project, shouldReturn, returnValue := verifyStorj(env, ctx)
	if shouldReturn {
		return nil, returnValue
	}

	download, err := project.DownloadObject(ctx, env.bucketName, env.objectKey, nil)
	if err != nil {
		return nil, fmt.Errorf("Object not found. You sure you're looking for the right thing? Could not download from bucket: %v", err)
	}

	defer download.Close()

	receivedContents, err := ioutil.ReadAll(download)
	if err != nil {
		return nil, fmt.Errorf("couldn't  read all download data: %v", err)
	}

	if !bytes.Equal(receivedContents, data) {
		return nil, fmt.Errorf("different object obtained: %q != %q", data, receivedContents)
	}
	return receivedContents, nil
}

func verifyStorj(env Env, ctx context.Context) (*uplink.Project, bool, error) {
	access, err := uplink.ParseAccess(env.accessGrant)
	if err != nil {
		return nil, true, fmt.Errorf("could not parse access grant: %v", err)
	}

	project, err := uplink.OpenProject(ctx, access)
	if err != nil {
		return nil, true, fmt.Errorf("couldn't open project: %v", err)
	}
	defer project.Close()

	_, err = project.EnsureBucket(ctx, env.bucketName)
	if err != nil {
		return nil, true, fmt.Errorf("could not ensure bucket exists: %v", err)
	}

	return project, false, nil
}

func GetBucketData() ([]byte, error) {

	env := getCapsaiBucketEnv()

	data, err := DownloadFromBucket(context.Background(), env, nil)
	if err != nil {
		return nil, fmt.Errorf("error downloading data: %v", err)
	}

	return data, nil
}