<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Service;

use StevenBuehner\ChurchTools\Api\GroupApi;
use StevenBuehner\sbChurchtoolsGrouphomepage\Always\MyContainer;
use StevenBuehner\sbChurchtoolsGrouphomepage\Vendor\Symfony\Contracts\Cache\ItemInterface;

class CtGroupService {

	/**
	 * @var array|bool
	 */
	protected mixed $groupsCached = FALSE;

	public function __construct(protected GroupApi $groupApi) {
	}

	public function getAllGroups() {

		if ($this->groupsCached === FALSE) {
			$cacheAdapter = MyContainer::getCacheAdapter();

			$cacheAdapter->clear('churchtools_api_all_groups');


			$this->groupsCached = $cacheAdapter->get('churchtools_api_all_groups', function (ItemInterface $item) {

				$item->expiresAfter(60); // 60 Sek
				$item->expiresAfter(1);

				$client = MyContainer::churchToolsLogin();
				$groups = $this
					->groupApi
					->getGroups(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, FALSE, FALSE, NULL, NULL, NULL, 1, 100)
					->getData();

				/** @var GetGroups200ResponseDataInner $g */
				$this->groupsCached = array_map(function ($g) {

					$temp = [
						'id'          => $g->getId(),
						'name'        => $g->getName(),
						'campus'      => $g->getInformation()->getCampusId(),
						'groupTypeId' => $g->getInformation()->getGroupTypeId(),
					];

					return $temp;

				}, $groups);


				return $this->groupsCached;

			});


		}

		return $this->groupsCached;
	}

	public function getGroupWithFields(int $groupId, ?array $filterGroupRoleIds = NULL) {

		MyContainer::churchToolsLogin();

		if (is_array($filterGroupRoleIds) && count($filterGroupRoleIds) === 0) {
			$filterGroupRoleIds = NULL;
		}

		$fields = $this->groupApi->getAllGroupMembers($groupId, $page = 1, $limit = 100, $filterGroupRoleIds)->getData();

		return $fields;

	}



}
