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

import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbsService, DetailsComponent, MasterDetailViewComponent } from '@bci-web-core/core';
import { Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { User } from '../../../shared/user';
import { UserService } from '../../../shared/user-service.service';

@Component({
  selector: 'bci-md-details',
  templateUrl: './md-details.component.html',
  styleUrls: ['./md-details.component.scss'],
})
export class MdDetailsComponent implements OnInit, OnDestroy, DetailsComponent {
  user: User;
  form: FormGroup = new FormGroup({});
  showDetailViewCloseIcon = true;

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

  constructor(
    public masterDetailView: MasterDetailViewComponent,
    private userService: UserService,
    private activatedRoute: ActivatedRoute,
    private formBuilder: FormBuilder,
    private snackBar: MatSnackBar,
    private breadcrumbsService: BreadcrumbsService
  ) {}

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      name: ['', [Validators.required]],
      role: [''],
      department: ['', [Validators.required]],
      email: ['', [Validators.required]],
    });

    // provide deep linking
    this.activatedRoute.params.pipe(takeUntil(this.componentDestroyed$)).subscribe((params) => {
      this.userService.querySingle(params['id']).subscribe((user) => {
        this.breadcrumbsService.setTemporaryTitleForPartialRoute(this.activatedRoute.snapshot, [':id'], user.name);
        this.user = user;
        if (user) {
          this.form.patchValue(user);
          this.masterDetailView.openDetails();
        }
      });
    });

    this.userService.showDetailsViewCloseIcon.subscribe(data => this.showDetailViewCloseIcon = data);
  }

  save() {
    if (this.form.touched && this.form.valid) {
      this.user = this.userService.upsert(Object.assign(new User(), this.user, this.form.value));
      this.form.patchValue(this.user);
      this.form.reset();
    }
  }

  cancel() {
    this.form.reset();
  }

  canCloseDetails(): boolean {
    if (this.form.dirty) {
      this.snackBar.open('To close the details, save your changes first.', '', <MatSnackBarConfig>{ duration: 5000 });
      return false;
    } else {
      return true;
    }
  }

  closeDetails(): boolean | Observable<boolean> {
    return this.masterDetailView.closeDetails();
  }

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