// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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
//
//      http://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.

// This file supports generating unique IDs so that multiple test executions
// don't interfere with each other, and cleaning up old entities that may
// remain if tests exit early.

package logging

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"testing"
	"time"
)

var (
	startTime       = time.Now()
	uniqueIDCounter int
	// Items older than expiredAge are remnants from previous tests and can be deleted.
	expiredAge = 24 * time.Hour
)

// uniqueID generates unique IDs so tests don't interfere with each other.
// All unique IDs generated in the same test execution will have the same timestamp.
func uniqueID(prefix string) string {
	uniqueIDCounter++
	// Zero-pad the counter for lexical sort order.
	return fmt.Sprintf("%s-t%d-%04d", prefix, startTime.UnixNano(), uniqueIDCounter)
}

// expiredUniqueIDs returns a subset of ids that are unique IDs as generated by
// uniqueID(prefix) and are older than expiredAge.
func expiredUniqueIDs(ids []string, prefix string) []string {
	var expired []string
	for _, id := range ids {
		t, ok := extractTime(id, prefix)
		if ok && time.Since(t) > expiredAge {
			expired = append(expired, id)
		}
	}
	return expired
}

// extractTime extracts the timestamp of s, which must begin with prefix and
// match the form generated by uniqueID. The second return value is true on
// success, false if there was a problem.
func extractTime(s, prefix string) (time.Time, bool) {
	if !strings.HasPrefix(s, prefix+"-t") {
		return time.Time{}, false
	}
	s = s[len(prefix)+2:]
	i := strings.Index(s, "-")
	if i < 0 {
		return time.Time{}, false
	}
	nanos, err := strconv.ParseInt(s[:i], 10, 64)
	if err != nil {
		return time.Time{}, false
	}
	return time.Unix(0, nanos), true
}

func TestExtractTime(t *testing.T) {
	uid := uniqueID("unique-ID")
	got, ok := extractTime(uid, "unique-ID")
	if !ok {
		t.Fatal("got ok = false, want true")
	}
	if !startTime.Equal(got) {
		t.Errorf("got %s, want %s", got, startTime)
	}

	got, ok = extractTime("p-t0-doesnotmatter", "p")
	if !ok {
		t.Fatal("got false, want true")
	}
	if want := time.Unix(0, 0); !want.Equal(got) {
		t.Errorf("got %s, want %s", got, want)
	}
	if _, ok = extractTime("invalid-time-1234", "invalid"); ok {
		t.Error("got true, want false")
	}
}

func TestExpiredUniqueIDs(t *testing.T) {
	const prefix = "uid"
	// The freshly unique IDs will have startTime as their timestamp.
	uids := []string{uniqueID(prefix), "uid-tinvalid-1234", uniqueID(prefix), "uid-t0-1111"}

	// This test hasn't been running for very long, so only the last ID is expired.
	got := expiredUniqueIDs(uids, prefix)
	want := []string{uids[3]}
	if !reflect.DeepEqual(got, want) {
		t.Errorf("got %v, want %v", got, want)
	}

	time.Sleep(100 * time.Millisecond)

	prev := expiredAge
	expiredAge = 10 * time.Millisecond
	defer func() { expiredAge = prev }()
	// This test has been running for at least 10ms, so all but the invalid ID have expired.
	got = expiredUniqueIDs(uids, prefix)
	want = []string{uids[0], uids[2], uids[3]}
	if !reflect.DeepEqual(got, want) {
		t.Errorf("got %v, want %v", got, want)
	}
}
