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

import {
  Component,
  ComponentFactoryResolver,
  ComponentRef,
  EventEmitter,
  Input,
  OnInit,
  Output,
  ViewChild,
  ViewContainerRef,
} from '@angular/core';
import { AlertService, AlertType, PrimaryButton } from '@bci-web-core/core';
import { WidgetTypes } from '../models/definitions';
import { Widget } from '../models/widget';
import { WidgetContentComponent } from '../models/widget-content-component';
import { PinboardI18nService } from '../services/pinboard-i18n.service';

@Component({
  selector: 'bci-widget',
  templateUrl: './widget.component.html',
  styleUrls: ['./widget.component.scss'],
})
export class WidgetComponent implements OnInit {
  @Input() widget: Widget;
  @Input() readOnly = false;
  @ViewChild('contentContainer', { read: ViewContainerRef, static: true }) private contentContainer: ViewContainerRef;
  public contentComponent: ComponentRef<WidgetContentComponent>;
  @Output() remove = new EventEmitter<Widget>();
  @Output() openEdit = new EventEmitter<Widget>();
  @Output() sizeChange = new EventEmitter<Widget>();
  @Output() linkToFilter = new EventEmitter<Widget>();

  public editModeActiveFor: Widget;
    /** When true, then the css style 'pointer-events: none' is applied*/
  @Input()
  public draggable = true;

  constructor(
    private cmpFctReslv: ComponentFactoryResolver,
    public pinboardI18n: PinboardI18nService,
    private alertService: AlertService,
    private viewContainerRef: ViewContainerRef
  ) {}

  /**
   * Creates WidgetContentComponent
   */
  ngOnInit() {
    const widgetType = this.widget.widgetDefinition.widgetType;
    const contentType = WidgetTypes.find((def) =>
      this.compareCaseInsensitive(widgetType, def.widgetType)
    ).contentComponentType;
    const contentFactory = this.cmpFctReslv.resolveComponentFactory(contentType);
    this.contentComponent = this.contentContainer.createComponent(contentFactory); // as ComponentRef<WidgetContentComponent>;
    this.contentComponent.instance.widget = this.widget;
  }

  /**
   * Destroys WidgetContentComponent and emits remove event
   */
  public removeWidget(): void {
    const confirmDialog = this.alertService.openAlertBox({
      title: this.pinboardI18n.deleteConfirmTitle,
      description: this.pinboardI18n.deleteConfirmDescription,
      type: AlertType.None,
      leftButtonTitle: this.pinboardI18n.delete,
      rightButtonTitle: this.pinboardI18n.cancel,
      primaryButton: PrimaryButton.RightButton,
    }, this.viewContainerRef);

    confirmDialog.afterClosed().subscribe((result) => {
      if (result === PrimaryButton.LeftButton) {
        this.remove.emit(this.widget);
        this.contentComponent.destroy();
      }
    });
  }

  /**
   * Emits openEdit event to open the SettingsSidebar
   */
  public editWidget(): void {
    this.openEdit.emit(this.widget);
  }

  /**
   * Triggers contentComponents resize event
   */
  public resize(): void {
    this.contentComponent.instance.resize();
  }

  /**
   * Called when the user selects a size configuration from the widget menu
   */
  onResizeWidget(newSizeArray: number[]) {
    this.widget.sizeArray = newSizeArray;
    this.sizeChange.emit(this.widget);
  }

  get showBurgerMenu(): boolean {
    return !this.readOnly && (this.widget.widgetDefinition.canEdit || this.widget.widgetDefinition.canRemove);
  }

  toggleLinkToFilter() {
    this.widget.isLinkedToFilter = !this.widget.isLinkedToFilter;
    this.widget.setUserSettingValue({ id: 'isLinkedToFilter' }, this.widget.isLinkedToFilter);
    if (!this.widget.isLinkedToFilter) {
      this.widget.widgetFilters = [];
    }
    this.linkToFilter.emit(this.widget);
  }

  private compareCaseInsensitive(a: string, b: string): boolean {
    return a.localeCompare(b, undefined, { sensitivity: 'base' }) === 0;
  }
}
