package adb

import (
	"os/exec"
	"path/filepath"

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

func adbFromPath(dirPath string, err error) (*Adb, error) {
	if err != nil {
		return nil, err
	}
	binPath := filepath.Join(dirPath, "adb")
	if err = misc.TestFile(binPath); err != nil {
		return nil, err
	}
	return &Adb{binPath: binPath}, nil
}

// NewAdbFind finds adb bin file (in $PATH) and creates Adb if bin file founds
func NewAdbFind() (*Adb, error) {
	if p, err := findAdbBin(); err != nil {
		return nil, err
	} else {
		return &Adb{
			binPath: p,
		}, nil
	}
}

// NewAdbFromSdk finds adb bin file in sdk.SDK and created Adb if bin file founds
func NewAdbFromSdk(sdk sdk.SDK) (*Adb, error) {
	return adbFromPath(sdk.PlatformTools())
}

// NewAdbFromPath creates Adb from path to bin file
func NewAdbFromPath(binPath string) (*Adb, error) {
	if err := misc.TestFile(binPath); err != nil {
		return nil, err
	} else {
		return &Adb{
			binPath: binPath,
		}, nil
	}
}

func findAdbBin() (string, error) {
	return exec.LookPath("adb")
}

func NewDevice(serial, dType, usb, product, model, device, transport string) Device {
	return Device{
		serial:      serial,
		deviceType:  dType,
		usb:         usb,
		product:     product,
		model:       model,
		device:      device,
		transportId: transport,
	}
}
