package shell

import (
	"fmt"
	"regexp"
	"strconv"
)

func (d DeviceShell) wm(args ...string) ([]byte, error) {
	return d.RunSync("wm", args...)
}

// GetScreenSize returns array with width (index 0) and height (index 1) for device's screen
func (d DeviceShell) GetScreenSize() ([2]int, error) {
	if outRaw, err := d.wm("size"); err != nil {
		return [...]int{-1, -1}, err
	} else {
		reg := regexp.MustCompile(`(\d+)x(\d+)`)
		if groups := reg.FindSubmatch(outRaw); len(groups) == 3 {
			return parseWmOut(groups)
		} else {
			return [...]int{-1, -1}, fmt.Errorf("cannot parse %q with regexp %q", outRaw, reg.String())
		}
	}
}

func (d DeviceShell) GetScreenWidth() (int, error) {
	hw, err := d.GetScreenSize()
	return hw[0], err
}

func (d DeviceShell) GetScreenHight() (int, error) {
	hw, err := d.GetScreenSize()
	return hw[1], err
}

func parseWmOut(groups [][]byte) ([2]int, error) {
	w, err := strconv.Atoi(string(groups[1]))
	if err != nil {
		return [...]int{-1, -1}, err
	}

	h, err := strconv.Atoi(string(groups[2]))
	if err != nil {
		return [...]int{-1, -1}, err
	}
	return [...]int{w, h}, nil
}
