/*
 Copyright 2023 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

import (
	"testing"

	. "gopkg.in/check.v1"

	testibus "gitlab.com/ubports/development/core/lomiri-push-service/bus/testing"
	"gitlab.com/ubports/development/core/lomiri-push-service/click"
	clickhelp "gitlab.com/ubports/development/core/lomiri-push-service/click/testing"
	helpers "gitlab.com/ubports/development/core/lomiri-push-service/testing"
	"gitlab.com/ubports/development/core/lomiri-push-service/testing/condition"
)

func TestFocusInfo(t *testing.T) { TestingT(t) }

type focusSuite struct {
	log *helpers.TestLogger
	app *click.AppId
}

var _ = Suite(&focusSuite{})

func (hs *focusSuite) SetUpTest(c *C) {
	hs.log = helpers.NewTestLogger(c, "debug")
	hs.app = clickhelp.MustParseAppId("com.example.test_test-app_0")
	GetPrimaryPID = func (appId *click.AppId) int {
		return 42
	}
}

// Checks that isPidFocused() actually calls isPidFocused
func (fs *focusSuite) TestGetsFocusInfo(c *C) {
	endp := testibus.NewTestingEndpoint(nil, condition.Work(true), true)
	ec := New(endp, fs.log)
	c.Check(ec.isPIDFocused(42), DeepEquals, true)
	callArgs := testibus.GetCallArgs(endp)
	c.Assert(callArgs, HasLen, 1)
	c.Check(callArgs[0].Member, Equals, "isPidFocused")
	c.Check(callArgs[0].Args, DeepEquals, []interface{}{uint32(42)})
}

var isFocusedTests = []struct {
	expected bool
	focused  bool
	pid      int
}{
	{
		false,
		false,
		0, // no running app
	},
	{
		true,
		true,
		42, // running app, focused
	},
	{
		false,
		false,
		42, // running app, not focused
	},
	{
		false,
		true,
		0, // invalid: no running app, but focus true
	},
}

// Check that if the app is focused, IsAppFocused returns true
func (fs *focusSuite) TestIsAppFocused(c *C) {
	for _, t := range isFocusedTests {
		endp := testibus.NewTestingEndpoint(nil, condition.Work(true), t.focused)
		ec := New(endp, fs.log)
		GetPrimaryPID = func (appId *click.AppId) int {
			return t.pid
		}
		c.Check(ec.IsAppFocused(fs.app), Equals, t.expected)
	}
}
