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

import { Component, OnDestroy, OnInit, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { User } from '../../../shared/user';
import { UserService } from '../../../shared/user-service.service';
import { AlertService, AlertType, BciAlertDialogIntl, PrimaryButton } from '@bci-web-core/core';

@Component({
  selector: 'bci-master-detail-demo',
  templateUrl: './md-list-demo.component.html',
  styleUrls: ['./md-list-demo.component.scss'],
  providers: [BciAlertDialogIntl],
})
export class MdListDemoComponent implements OnInit, OnDestroy {
  modalResponse: string;
  showLoading = true;
  public _lastQuery: Params | undefined;
  masterViewMinSize: number;
  detailViewMinSize: number;
  detailViewSize: number;

  protected componentDestroyed$ = new Subject<void>();

  constructor(
    public userService: UserService,
    public alertService: AlertService,
    private route: ActivatedRoute,
    private router: Router,
    private viewContainerRef: ViewContainerRef
  ) {}

  closeTrigger = () => this.router.navigate(['.'], { relativeTo: this.route });

  ngOnInit(): void {
    this.userService.items.pipe(takeUntil(this.componentDestroyed$)).subscribe(() => (this.showLoading = false));
    this.route.queryParams.pipe(takeUntil(this.componentDestroyed$)).subscribe((params) => {
      this.userService.queryAll(params);
    });

    const url = this.router.url.split('/');
    url.length > 3 && this.setSelectedUser(url[url.length-1]);
  }

  ngOnDestroy(): void {
    this.componentDestroyed$.next();
    this.componentDestroyed$.complete();
  }

  addUser() {
    const newUser = Math.floor(Math.random() * 1000 + this.userService.sampleData.length);
    const id = newUser.toString();
    this.userService.sampleData.push(
      new User(id, 'User ' + id, 'User', 'IT', 'user' + id + '@company.com', new Date())
    );
    this.userService.queryAll(this._lastQuery);
  }

  deleteUser(user: { name: string; id: string }) {
    this.modalResponse = null;
    const ref = this.alertService.openAlertBox({
      type: AlertType[Symbol.hasInstance],
      title: `Delete ${user.name}?`,
      description: 'This action will delete this User.',
      leftButtonTitle: 'Delete',
      rightButtonTitle: 'Cancel',
      primaryButton: PrimaryButton.LeftButton,
    }, this.viewContainerRef);
    ref.afterClosed().subscribe((res) => {
      this.modalResponse = res;
      if (res === 'left') {
        const index = this.userService.sampleData.findIndex((value) => value.id === user.id);
        this.userService.sampleData = this.userService.sampleData.filter(
          (value) => this.userService.sampleData.indexOf(value) !== index
        );
        this.userService.queryAll(this._lastQuery);
        this.closeTrigger();
      }
    });
  }

  private setSelectedUser(id:string) {
    const userToSelect = this.userService.sampleData.find(user => user.id === id);
    userToSelect.selected = true;
    this.userService.queryAll(this._lastQuery);
  }
}
