package sdk

import (
	"fmt"
	"os"
	"path"
	"sort"

	"notabug.org/Umnik/GoAndroidSDK/v2/components/misc"
)

// SDK represents Android SDK
type SDK struct {
	dirPath string
}

// RootDir returns path to SDK dir
func (s SDK) RootDir() string {
	return s.dirPath
}

func testDir(dir string) (string, error) {
	if err := misc.TestDir(dir); err != nil {
		return "", err
	}
	return dir, nil
}

// PlatformTools returns path to "platform-tools" dir
func (s SDK) PlatformTools() (string, error) {
	return testDir(path.Join(s.RootDir(), "platform-tools"))
}

// BuildTools returns path to "build-tools" dir
func (s SDK) BuildTools() (string, error) {
	return testDir(path.Join(s.RootDir(), "build-tools"))
}

// Platforms returns path to platforms directory
func (s SDK) Platforms() (string, error) {
	return testDir(path.Join(s.RootDir(), "platforms"))
}

// SystemImages returns path to systemImages catalog
func (s SDK) SystemImages() (string, error) {
	return testDir(path.Join(s.RootDir(), "system-images"))
}

// LastBuildToolsVersion returns path to last available version in "build-tools" dir
func (s SDK) LastBuildToolsVersion() (string, error) {
	if p, err := s.BuildTools(); err != nil {
		return "", err
	} else {
		if dirEntries, err := os.ReadDir(p); err != nil {
			return "", fmt.Errorf("cannot find last build-tools version due error: %v", err)
		} else {
			versions := make([]string, len(dirEntries))

			for i := range dirEntries {
				versions[i] = dirEntries[i].Name()
			}

			sort.Strings(versions)
			return s.SpecificBuildToolsVersion(versions[len(versions)-1])
		}
	}
}

// SpecificBuildToolsVersion returns path to specified version in "build-tools" dir
func (s SDK) SpecificBuildToolsVersion(version string) (string, error) {
	return testDir(path.Join(s.RootDir(), "build-tools", version))
}

// SpecificPlatformsVersion returns path to specific version in "platforms" dir
func (s SDK) SpecificPlatformsVersion(version string) (string, error) {
	if p, err := s.Platforms(); err != nil {
		return "", err
	} else {
		return testDir(path.Join(p, version))
	}
}
