package adb

import (
	"log"
	"strings"

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

// Adb represents adb util
type Adb struct {
	binPath string
}

// Device represents Android device
type Device struct {
	serial      string
	deviceType  string
	usb         string
	product     string
	model       string
	device      string
	transportId string
}

func (d Device) Serial() string {
	return d.serial
}

func (adb Adb) BinPath() string {
	return adb.binPath
}

func (adb Adb) Version() ([]byte, error) {
	return executor.RunSync(adb, "version")
}

func (adb Adb) KillServer() ([]byte, error) {
	return executor.RunSync(adb, "kill-server")
}

func (adb Adb) ConnectedDevices() (devices []Device) {
	data, err := executor.RunSync(adb, "devices", "-l")
	if err != nil {
		log.Println(err)
		return nil
	}

	for _, rawLineDevice := range deviceLines(data) {
		var deviceDescription [7]string
		for _, part := range strings.Split(rawLineDevice, " ") {
			part = strings.TrimSpace(part)
			if len(part) == 0 {
				continue
			}
			switch {
			default:
				deviceDescription[0] = part
			case strings.HasPrefix(part, "device") || (strings.HasPrefix(part, "emulator") && !strings.HasPrefix(part, "emulator-")):
				deviceDescription[1] = part
			case strings.HasPrefix(part, "usb:"):
				deviceDescription[2] = misc.TwoSpotValue(part)
			case strings.HasPrefix(part, "product:"):
				deviceDescription[3] = misc.TwoSpotValue(part)
			case strings.HasPrefix(part, "model:"):
				deviceDescription[4] = misc.TwoSpotValue(part)
			case strings.HasPrefix(part, "device:"):
				deviceDescription[5] = misc.TwoSpotValue(part)
			case strings.HasPrefix(part, "transport_id:"):
				deviceDescription[6] = misc.TwoSpotValue(part)
			}
		}
		devices = append(devices, NewDevice(deviceDescription[0],
			deviceDescription[1],
			deviceDescription[2],
			deviceDescription[3],
			deviceDescription[4],
			deviceDescription[5],
			deviceDescription[6]))
	}
	return
}

func deviceLines(data []byte) (result []string) {
	for _, line := range strings.Split(string(data), "\n") {
		line = strings.TrimSpace(line)
		if len(line) == 0 || strings.HasPrefix(line, "List of") {
			continue
		}
		result = append(result, line)
	}
	return
}
