package fire

import (
	"context"
	"errors"
	"strings"
	"time"

	"cloud.google.com/go/firestore"
	firebase "firebase.google.com/go"
)

// getContextValue returns value of the specified key from context
func getContextValue(ctx context.Context, key string) (string, bool) {
	value, ok := ctx.Value(key).(string)
	return value, ok
}

// ColRef returns collection reference
func ColRef(client *firestore.Client, names ...string) *firestore.CollectionRef {
	path := strings.Join(names, "/")
	return client.Collection(path)
}

// DocRef returns document reference
func DocRef(client *firestore.Client, names ...string) *firestore.DocumentRef {
	path := strings.Join(names, "/")
	return client.Doc(path)
}

// NowMM returns now time of Myanmar Timezone
func NowMM() (*time.Time, error) {
	loc, err := time.LoadLocation("Asia/Rangoon")
	if err != nil {
		return nil, err
	}
	//set timezone,
	now := time.Now().In(loc)
	return &now, nil
}

// TimestampMilli returns time in milli seconds
func TimestampMilli(t time.Time) int64 {
	return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func getDocWithID(ctx context.Context, ref *firestore.DocumentRef) (map[string]interface{}, error) {
	snap, err := ref.Get(ctx)
	if err != nil {
		return nil, err
	}
	doc := snap.Data()
	doc["id"] = snap.Ref.ID
	return doc, nil
}

// SetClaim set claims to user
func SetClaim(ctx context.Context, app *firebase.App, phoneNumber string, claims map[string]interface{}) error {
	client, err := app.Auth(ctx)
	if err != nil {
		return errors.New("error getting Auth client: " + err.Error())
	}

	user, err := client.GetUserByPhoneNumber(ctx, phoneNumber)
	if err != nil {
		return errors.New("error getting user by phone: " + err.Error())
	}

	_claims := make(map[string]interface{})
	for k, v := range user.CustomClaims {
		_claims[k] = v
	}
	for k, v := range claims {
		_claims[k] = v
	}

	// fmt.Println("all claims:", _claims)
	err = client.SetCustomUserClaims(ctx, user.UID, _claims)
	if err != nil {
		return errors.New("error set customer claim: " + err.Error())
	}
	return nil
}