import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IPredefinedReplyCategoryModel } from '@fleio-api/plugins/tickets/model/predefined-reply-category.model';
import { PredefinedReplyCategoryApiService } from '@fleio-api/plugins/tickets/predefined-reply-category-api.service';

@Component({
  selector: 'app-predefined-reply-category-edit-form',
  templateUrl: './predefined-reply-category-edit-form.component.html',
  styleUrls: ['./predefined-reply-category-edit-form.component.scss']
})
export class PredefinedReplyCategoryEditFormComponent extends DetailsFormBase<IPredefinedReplyCategoryModel> implements OnInit {
  predefinedReplyCategoryForm = this.formBuilder.group({
    name: ['', Validators.required],
  });


  constructor(
    private formBuilder: UntypedFormBuilder, private activatedRoute: ActivatedRoute, private config: ConfigService,
    private predefinedReplyCategoryApiService: PredefinedReplyCategoryApiService, private router: Router,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveCategory();
    }
    if (this.object) {
      this.predefinedReplyCategoryForm.patchValue(this.object);
    }
  }

  private saveCategory(): Observable<IActionResult> {
    const value = this.predefinedReplyCategoryForm.value as any;

    this.createOrUpdate(this.predefinedReplyCategoryApiService, value).subscribe(() => {
      this.router.navigateByUrl(
        this.config.getPrevUrl('tickets/predefined-replies')
      ).catch(() => {
      });
    });

    return of(null);
  }
}
