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

import { DataSource } from '@angular/cdk/collections';
import { Component, OnDestroy, OnInit, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { AlertService, AlertType, BciAlertDialogIntl, PrimaryButton } from '@bci-web-core/core';
import { PageEvent } from '@bci-web-core/web-components/dist';
import { Observable, fromEvent } from 'rxjs';
import { map, skip, startWith, takeUntil } from 'rxjs/operators';
import { User } from '../../../shared/user';
import { UserService } from '../../../shared/user-service.service';
import { MdListDemoComponent } from '../md-list-demo/md-list-demo.component';

/*
  The material-table requires a DataSource.
  Wrapping UserService does the job.
 */
class TableDataSource implements DataSource<User> {
  constructor(private userService: UserService) {}

  connect(): Observable<User[]> {
    this.loadUsers();
    return this.userService.items;
  }

  // eslint-disable-next-line no-empty-function
  disconnect() {}

  loadUsers(params?: Params) {
    this.userService.queryAll(params);
  }
}

@Component({
  selector: 'bci-md-table-demo',
  templateUrl: './md-table-demo.component.html',
  styleUrls: ['./md-table-demo.component.scss'],
  providers: [BciAlertDialogIntl],
})
export class MdTableDemoComponent extends MdListDemoComponent implements OnInit, OnDestroy {
  displayedColumns = ['id', 'name', 'department', 'email', 'actions'];
  pageSize = 3;
  pageSizeOptions = [3, 5, 10];
  dataSource: TableDataSource;
  showLoading = true;
  modalResponse: string;
  public _lastQuery: Params | undefined;

  isMobile$: Observable<boolean>;
  checkScreenSize = (): boolean => document.body.offsetWidth < 768;

  constructor(
    public userService: UserService,
    public alertService: AlertService,
    route: ActivatedRoute,
    router: Router,
    private viewContainterReference: ViewContainerRef
  ) {
    super(userService, alertService, route, router, viewContainterReference);
    route.queryParamMap.pipe(skip(1)).subscribe(() => (this.showLoading = true));
  }

  ngOnInit() {
    this.masterViewMinSize = 390;
    this.detailViewMinSize = 250;
    this.userService.pageSize = this.pageSize;
    this.dataSource = new TableDataSource(this.userService);
    this.dataSource
      .connect()
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe(() => (this.showLoading = false));

    const screenSizeChanged$ = fromEvent(window, 'resize').pipe(map(this.checkScreenSize));
    this.isMobile$ = screenSizeChanged$.pipe(startWith(this.checkScreenSize()));
    super.ngOnInit();
  }

  ngOnDestroy() {
    // reset pageSize because same service instance is used in other examples
    this.userService.pageSize = 500;
    super.ngOnDestroy();
  }

  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);
  }

  onPageChange(pageEvent: PageEvent) {
    this.userService.pageSize = pageEvent.pageSize;
    this.userService.queryAll({ page: pageEvent.pageIndex });
  }

  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.RightButton,
    }, this.viewContainterReference);
    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);
      }
    });
  }
}
