/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Injectable } from '@angular/core';
import { CommandbarItemComponent } from './commandbar-item.component';
import { BreakpointObserver } from '@angular/cdk/layout';

export interface VisibilitySortResult<T> {
  visible: T[];
  hidden: T[];
}

@Injectable()
export class CommandbarItemVisibilityService {
  constructor(private breakpointObserver: BreakpointObserver) {}

  sort<T extends CommandbarItemComponent>(items: T[]): VisibilitySortResult<T> {
    const visible = [];
    const hidden = [];
    items.forEach((item) => (this.trueOrMatchesMediaState(item.hide) ? hidden.push(item) : visible.push(item)));
    return {
      visible: visible,
      hidden: hidden,
    };
  }

  private trueOrMatchesMediaState(queryOrIsHidden: string | string[] | boolean) {
    if (queryOrIsHidden === undefined) {
      return false;
    } else if (queryOrIsHidden === null) {
      return true;
    } else if (typeof queryOrIsHidden === 'boolean') {
      return queryOrIsHidden;
    } else {
      return queryOrIsHidden.length === 0 || this.breakpointObserver.isMatched(queryOrIsHidden);
    }
  }
}
