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

import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Component, Inject, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { PinboardConfig } from '@bci-web-core/pinboard';

@Component({
  selector: 'bci-dashboard-settings',
  templateUrl: './dashboard-settings.component.html',
  styleUrls: ['./dashboard-settings.component.scss'],
})
export class DashboardSettingsComponent implements OnInit {
  dashboards: PinboardConfig[];
  deletedDashboards: string[] = [];
  defaultLabel = 'Dashboard';
  maxDashboardLabelLength = 30;

  dashboardForm = this.fb.group({
    dashboardLabels: this.fb.array([]),
  });

  constructor(
    public dialogRef: MatDialogRef<DashboardSettingsComponent>,
    private fb: FormBuilder,
    @Inject(MAT_DIALOG_DATA) private data: any
  ) {}

  ngOnInit(): void {
    this.dashboards = this.data.dashboards;

    for (let i = 0; i <= this.dashboards.length - 1; i++) {
      this.dashboardLabels.push(
        this.fb.group({
          id: this.fb.control(this.dashboards[i].id),
          label: this.fb.control(this.dashboards[i].label, Validators.required),
          priority: this.fb.control(i),
        })
      );
    }
  }

  get dashboardLabels(): FormArray {
    return this.dashboardForm.get('dashboardLabels') as FormArray;
  }

  addPinboard(): void {
    this.dashboardLabels.push(
      this.fb.group({
        id: this.fb.control(''),
        label: this.fb.control(this.defaultLabel, Validators.required),
        priority: this.fb.control(null),
      })
    );
  }

  drop(event: CdkDragDrop<any[]>): void {
    moveItemInArray(this.dashboardLabels.controls, event.previousIndex, event.currentIndex);
  }

  removePinboard(index: number): void {
    const dashboardToDelete = this.dashboardLabels.controls[index] as FormGroup;
    if (dashboardToDelete.controls.id.value !== '') {
      this.deletedDashboards.push(dashboardToDelete.controls.id.value);
    }
    this.dashboardLabels.removeAt(index);
  }

  saveSettings(): void {
    const dashboards = this.dashboardLabels.controls.map((field: FormGroup, index: number) => {
      return {
        id: field.controls.id.value,
        label: field.controls.label.value,
        priority: index,
      };
    });

    this.dialogRef.close({
      created: dashboards.filter((item) => item.id === ''),
      updated: dashboards.filter((item) => item.id !== ''),
      deleted: this.deletedDashboards,
    });
  }

  closeSettings(): void {
    this.dialogRef.close();
  }
}
