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

import { BreakpointObserver } from '@angular/cdk/layout';
import { Directive, ElementRef, Input, OnDestroy, OnInit, Renderer2 } from '@angular/core';
import { Subject, takeUntil } from 'rxjs';
import { BOSCH_MEDIA_QUERIES } from './bosch-breakpoints';

/**
 * directive to add to elements which should be shown or hide in a certain viewport. Sets up a breakpoint observer and listens to viewport changes. 
 * 
 * @input bciShowHide - takes the media query string as input, it is recommended to use BOSCH_MEDIA_QUERIES
 * @input mode - show or hide - determines if the element should be shown or hide if the media query matches
 * @input display - css display attribute value which gets applied when the element is shown, default is block
 */
@Directive({ selector: '[bciShowHide]'})
export class BciShowHideDirective implements OnInit, OnDestroy {

  @Input() bciShowHide = '';
  @Input() mode: 'hide' | 'show';
  @Input() display = 'block';

  private directiveDestroyed$ = new Subject<void>();

  constructor(private el: ElementRef, private breakpointObserver: BreakpointObserver, private renderer: Renderer2) {}

  ngOnInit() {
    this.breakpointObserver
      .observe(getMediaQuery(this.bciShowHide))
      .pipe(takeUntil(this.directiveDestroyed$))
      .subscribe(() => {
        if (this.breakpointObserver.isMatched(getMediaQuery(this.bciShowHide))) {
          this.mode === 'hide' ? this.renderer.setStyle(this.el.nativeElement, 'display', 'none') : this.renderer.setStyle(this.el.nativeElement, 'display', this.display);
        } else {
          this.mode === 'hide' ? this.renderer.setStyle(this.el.nativeElement, 'display', this.display) : this.renderer.setStyle(this.el.nativeElement, 'display', 'none');
        }  
      });
  }

  ngOnDestroy() {
    this.directiveDestroyed$.next();
    this.directiveDestroyed$.complete();
  }

}

function getMediaQuery(query: string): string {
  switch (query) {
    case 'mobile':
      return BOSCH_MEDIA_QUERIES.mobile;
      break;
    case 'tablet':
      return BOSCH_MEDIA_QUERIES.tablet;
      break;
    case 'desktop':
      return BOSCH_MEDIA_QUERIES.desktop;
      break;
    default:
      console.error('Please select a Media Query for the BciShowHide directive (mobile, tablet or desktop)');
      break;
  }
}
