// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package firestore

import (
	"bytes"
	"context"
	"strings"
	"testing"

	"cloud.google.com/go/firestore"
	"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
)

func TestSave(t *testing.T) {
	testutil.EndToEndTest(t)
	// TODO: revert this to testutil.SystemTest(t).ProjectID
	// when datastore and firestore can co-exist in a project.
	projectID := getProjectID(t)

	ctx := context.Background()

	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		t.Fatal(err)
	}

	// TODO(someone): check values of docs to make sure data is being manipulated properly.
	if err = addDocAsMap(ctx, client); err != nil {
		t.Fatalf("addDocAsMap: %v", err)
	}
	if err = addDocDataTypes(ctx, client); err != nil {
		t.Fatalf("addDocDataTypes: %v", err)
	}
	if err = addDocAsEntity(ctx, client); err != nil {
		t.Fatalf("addDocAsEntity: %v", err)
	}
	if err = addDocWithID(ctx, client); err != nil {
		t.Fatalf("addDocWithID: %v", err)
	}
	if err = addDocWithoutID(ctx, client); err != nil {
		t.Fatalf("addDocWithoutID: %v", err)
	}
	if err = addDocAfterAutoGeneratedID(ctx, client); err != nil {
		t.Fatalf("addDocAfterAutoGeneratedID: %v", err)
	}
	if err = updateDoc(ctx, client); err != nil {
		t.Fatalf("updateDoc: %v", err)
	}
	if err = updateDocCreateIfMissing(ctx, client); err != nil {
		t.Fatalf("updateDocCreateIfMissing: %v", err)
	}
	if err = updateDocMultiple(ctx, client); err != nil {
		t.Fatalf("updateDocMultiple: %v", err)
	}
	if err = updateDocNested(ctx, client); err != nil {
		t.Fatalf("updateDocNested: %v", err)
	}
	if value, _, err := getField(ctx, client, "users", "frank", "favorites"); err != nil {
		t.Fatal(err)
	} else {
		favorites := value.(map[string]interface{})
		if got, want := favorites["color"], "Red"; got != want {
			t.Errorf("users/frank/favorites.color = %#v; want %#v", got, want)
		}
		if got, want := favorites["food"], "Pizza"; got != want {
			t.Errorf("users/frank/favorites.age = %#v; want %#v", got, want)
		}
	}

	if err = deleteDoc(ctx, client); err != nil {
		t.Fatalf("deleteDoc: %v", err)
	}

	if _, exists, err := getField(ctx, client, "cities", "BJ", "capital"); err != nil {
		t.Fatal(err)
	} else if !exists {
		t.Error("Expected 'cities/BJ/capital' to be present")
	}
	if err = deleteField(ctx, client); err != nil {
		t.Fatalf("deleteField: %v", err)
	}
	if _, exists, err := getField(ctx, client, "cities", "BJ", "capital"); err != nil {
		t.Fatal(err)
	} else if exists {
		t.Error("Expected 'cities/BJ/capital' to be deleted")
	}

	if err = runSimpleTransaction(ctx, client); err != nil {
		t.Fatalf("runSimpleTransaction: %v", err)
	}
	if _, err = infoTransaction(ctx, client); err != nil {
		t.Fatalf("infoTransaction: %v", err)
	}
	if err = batchWrite(ctx, client); err != nil {
		t.Fatalf("batchWrite: %v", err)
	}
	var buf bytes.Buffer
	if err := deleteCollection(&buf, projectID, "cities", 2); err != nil {
		t.Fatalf("Cannot delete collection %v", err)
	}
	got := buf.String()
	if !strings.Contains(got, "cities") {
		t.Errorf("wanted collection name in deleteCollection results")
	}
}

func getField(ctx context.Context, client *firestore.Client, collection, doc, field string) (value interface{}, exists bool, err error) {
	dsnap, err := client.Collection(collection).Doc(doc).Get(ctx)
	if err != nil {
		return nil, false, err
	}
	val, ok := dsnap.Data()[field]
	return val, ok, nil
}
