package protocol

import (
	"context"
	"net/url"
	"path"
)

type ServiceDefinition struct {
	ServiceType       string
	Identifier        string
	DisplayName       string
	RelativeToSetting string
	RelativePath      string
	Description       string
	ServiceOwner      string
	ResourceVersion   int
	MinVersion        string
	MaxVersion        string
}

type LocationServiceData struct {
	ServiceDefinitions []ServiceDefinition
}

type ConnectionData struct {
	LocationServiceData LocationServiceData
}

func (vssConnection *VssConnection) GetConnectionData() *ConnectionData {
	parsedURL, err := url.Parse(vssConnection.TenantURL)
	if err != nil {
		return nil
	}
	parsedURL.Path = path.Join(parsedURL.Path, "_apis/connectionData")
	q := parsedURL.Query()
	q.Add("connectOptions", "1")
	q.Add("lastChangeId", "-1")
	q.Add("lastChangeId64", "-1")
	parsedURL.RawQuery = q.Encode()
	connectionData := &ConnectionData{}
	err = vssConnection.RequestWithContext2(context.Background(), "GET", parsedURL.String(), "1.0", nil, connectionData)
	if err != nil {
		return nil
	}
	return connectionData
}

func (connectionData *ConnectionData) GetServiceDefinition(id string) *ServiceDefinition {
	for i := 0; i < len(connectionData.LocationServiceData.ServiceDefinitions); i++ {
		if connectionData.LocationServiceData.ServiceDefinitions[i].Identifier == id {
			return &connectionData.LocationServiceData.ServiceDefinitions[i]
		}
	}
	return nil
}
