package config

import (
	"github.com/elliotchance/pie/v2"
)

// GetGCPDualRegionCandidateSet get all gcp regions that can be paired with the region
// for details about gcp dual-region configuration, refer to https://cloud.google.com/storage/docs/locations#location-dr
func (b *BucketOptionsConfig) GetGCPDualRegionCandidateSet(region string) map[string]struct{} {
	dualRegionSet := make(map[string]struct{})
	if regions, ok := b.GCPBucketRestrictedDualRegions[region]; ok {
		for _, r := range regions {
			dualRegionSet[r] = struct{}{}
		}
		// for restricted paired regions, the region can only pair with these regions
		return dualRegionSet
	}

	for _, regions := range b.GCPBucketGeneralDualRegions {
		if !pie.Contains(regions, region) {
			continue
		}

		// regions with same location code can pair
		for _, r := range regions {
			dualRegionSet[r] = struct{}{}
		}
		break
	}

	for _, regions := range b.GCPBucketPredefinedDualRegions {
		if !pie.Contains(regions, region) {
			continue
		}

		// regions with same predefined dual-region name can pair
		for _, r := range regions {
			dualRegionSet[r] = struct{}{}
		}
	}

	delete(dualRegionSet, region)
	return dualRegionSet
}

func (b *BucketOptionsConfig) GetGCPDualRegionPredefinedName(region1, region2 string) string {
	for name, regions := range b.GCPBucketPredefinedDualRegions {
		if pie.Contains(regions, region1) && pie.Contains(regions, region2) {
			return name
		}
	}
	return ""
}

func (b *BucketOptionsConfig) GetGCPDualRegionLocationCode(region1, region2 string) string {
	for code, regions := range b.GCPBucketGeneralDualRegions {
		if pie.Contains(regions, region1) && pie.Contains(regions, region2) {
			return code
		}
	}
	return ""
}

// InitGCPDualRegionConfigForTest only used for ut
func InitGCPDualRegionConfigForTest() {
	Global().ServerConfig.BucketOptions.GCPBucketPredefinedDualRegions = map[string][]string{
		"asia1": {"asia-northeast1", "asia-northeast2"},
		"eur4":  {"europe-north1", "europe-west4"},
		"eur5":  {"europe-west1", "europe-west2"},
		"eur7":  {"europe-west2", "europe-west3"},
		"eur8":  {"europe-west3", "europe-west6"},
		"nam4":  {"us-central1", "us-east1"},
	}
	Global().ServerConfig.BucketOptions.GCPBucketGeneralDualRegions = map[string][]string{
		"asia": {"asia-east1", "asia-southeast1"},
		"au":   {"australia-southeast1", "australia-southeast2"},
		"ca":   {"northamerica-northeast1", "northamerica-northeast2"},
		"eu": {"europe-central2", "europe-north1", "europe-southwest1", "europe-west1",
			"europe-west3", "europe-west4", "europe-west8", "europe-west9"},
		"in": {"asia-south1", "asia-south2"},
		"us": {"us-central1", "us-east1", "us-east4", "us-east5",
			"us-south1", "us-west1", "us-west2", "us-west3", "us-west4"},
	}
	Global().ServerConfig.BucketOptions.GCPBucketRestrictedDualRegions = map[string][]string{
		"us-east5": {"us-central1", "us-east1"},
	}
}
