/*
 Copyright 2022 Guido Berhoerster <guido+ubports@berhoerster.name>

 This program is free software: you can redistribute it and/or modify it
 under the terms of the GNU General Public License version 3, as published
 by the Free Software Foundation.

 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranties of
 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along
 with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

// Package focusinfo retrieves information whether an app is focused using
// liblomiri-app-launch and the Lomiri Shell DBus API
package focusinfo

/*
#cgo pkg-config: lomiri-app-launch-0

#include <lomiri-app-launch.h>
#include <glib.h>
*/
import "C"

import (
	"unsafe"

	"gitlab.com/ubports/development/core/lomiri-push-service/bus"
	"gitlab.com/ubports/development/core/lomiri-push-service/click"
	"gitlab.com/ubports/development/core/lomiri-push-service/logger"
)

var BusAddress bus.Address = bus.Address{
	Interface: "com.lomiri.Shell.FocusInfo",
	Path:      "/com/lomiri/Shell/FocusInfo",
	Name:      "com.lomiri.Shell.FocusInfo",
}

// wrapper for lomiri_app_launch_get_primary_pid()
func getPrimaryPID(appId *click.AppId) int {
	var pid C.GPid

	app_id := C.CString(appId.String())
	defer C.free(unsafe.Pointer(app_id))
	pid = C.lomiri_app_launch_get_primary_pid(app_id)
	return (int)(pid)
}

var GetPrimaryPID = getPrimaryPID

type FocusInfo struct {
	bus bus.Endpoint
	log logger.Logger
}

func New(endp bus.Endpoint, log logger.Logger) *FocusInfo {
	return &FocusInfo{endp, log}
}

func (fi *FocusInfo) isPIDFocused(pid int) (isFocused bool) {
	if err := fi.bus.Call("isPidFocused", bus.Args(uint32(pid)), &isFocused); err != nil {
		fi.log.Errorf("isPidFocused call returned %v", err)
	}
	return
}

func (fi *FocusInfo) IsAppFocused(appId *click.AppId) bool {
	pid := GetPrimaryPID(appId)
	if pid == 0 {
		return false
	}
	return fi.isPIDFocused(pid)
}
