import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { PredefinedReplyCategoryApiService } from '@fleio-api/plugins/tickets/predefined-reply-category-api.service';
import { IPredefinedReplyCategoryModel } from '@fleio-api/plugins/tickets/model/predefined-reply-category.model';
import { IPredefinedReplyModel } from '@fleio-api/plugins/tickets/model/predefined-reply.model';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';

@Component({
  selector: 'app-insert-predefined-reply-dialog',
  templateUrl: './insert-predefined-reply-dialog.component.html',
  styleUrls: ['./insert-predefined-reply-dialog.component.scss']
})
export class InsertPredefinedReplyDialogComponent implements IBaseDialog, OnInit {
  loading = false;
  loadingReplies = false;
  predefinedReplyCategories: Array<IPredefinedReplyCategoryModel>;
  predefinedReplies: Array<IPredefinedReplyModel>;
  dialogTitle = $localize`Insert predefined reply`;
  dialogActions: Array<IAction> = [];

  constructor(
    public dialogRef: MatDialogRef<InsertPredefinedReplyDialogComponent>,
    private predefinedReplyCategoryApiService: PredefinedReplyCategoryApiService,
  ) { }

  insert(predefinedReply: IPredefinedReplyModel) {
    this.dialogRef.close(predefinedReply.content);
  }

  openedExpansionPanel(category: IPredefinedReplyCategoryModel) {
    this.predefinedReplies = null;
    this.loadingReplies = true;
    this.predefinedReplyCategoryApiService.getPredefinedReplies(
      category.id, 1, 10000,
    ).subscribe(
      response => {
      this.predefinedReplies = response.objects;
    }).add(() => {
      this.loadingReplies = false;
    });
  }

  ngOnInit(): void {
    this.loading = true;
    this.predefinedReplyCategoryApiService.list(
      {page_size: 10000, ordering: 'name'}
    ).subscribe(response => {
      this.predefinedReplyCategories = response.objects;
    }).add(() => {
      this.loading = false;
    });
  }

}
