import { Group } from "models";
import { filterByLastActive } from "pbHelpers/Device";

export function groupsAreEqual(g1: Group, g2: Group): boolean {
  return (
    JSON.stringify(g1.settings.toJSON()) === JSON.stringify(g2.settings.toJSON()) &&
    JSON.stringify(g1.status.toJSON()) === JSON.stringify(g2.status.toJSON())
  );
}

//complex filter algorithm for searching a list of groups
export function filterGroups(searchValue: string, groups: Group[]): Group[] {
  return groups.filter(g => filterGroup(searchValue.toLowerCase(), g));
}

export function filterGroup(searchValue: string, group: Group): boolean {
  const idMatch: boolean = filterByGroupID(searchValue, group.settings.groupId);
  const nameMatch: boolean = filterByGroupName(searchValue, group.name());
  const lastActiveMatch: boolean = filterByLastActive(searchValue, group.status.lastActive);
  return idMatch || nameMatch || lastActiveMatch;
}

export function filterByGroupID(searchValue: string, groupID?: number | Long | null): boolean {
  let groupIDString = groupID ? groupID.toString() : "";
  return groupIDString === searchValue.replace("id:", "").trim();
}

export function filterByGroupName(searchValue: string, name: string): boolean {
  return (
    name.toLowerCase().indexOf(
      searchValue
        .replace("name:", "")
        .trim()
        .toLowerCase()
    ) > -1
  );
}
