import { Component, OnDestroy, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormArray, UntypedFormBuilder, UntypedFormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { Observable, of, Subscription } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ITicketDepartmentModel } from '@fleio-api/plugins/tickets/model/ticket-department.model';
import { IDepartmentCreateOptionsModel } from '@fleio-api/plugins/departments/model/department-create-options.model';
import { TicketDepartmentsApiService } from '@fleio-api/plugins/tickets/ticket-departments-api.service';

@Component({
  selector: 'app-department-edit-form',
  templateUrl: './department-edit-form.component.html',
  styleUrls: ['./department-edit-form.component.scss']
})
export class DepartmentEditFormComponent extends DetailsFormBase<ITicketDepartmentModel> implements OnInit, OnDestroy {
  departmentForm = this.formBuilder.group({
    name: ['', Validators.required],
    email: ['', [Validators.required, Validators.maxLength(127), Validators.email]],
    additional_emails: [''],
    ticket_id_format: ['', Validators.required],
    notification_to_user_on_ticket_opened: [true, Validators.required],
    notification_to_user_on_ticket_closed: [true, Validators.required],
    notification_on_staff_user_reply_to_user: [true, Validators.required],
    notify_cc_recipients_on_ticket_open: [true, Validators.required],
    notify_cc_recipients_on_ticket_close: [true, Validators.required],
    notify_cc_recipients_on_ticket_reply: [true, Validators.required],
    staff_ticket_notifications_settings: this.formBuilder.array([]),
  });
  createOptions: IDepartmentCreateOptionsModel;
  fullYearTxt = $localize`Full year (e.g. 2019)`;
  yearTxt = $localize`Year (e.g. 19)`;
  monthTxt = $localize`Month`;
  dayTxt = $localize`Day`;
  hourTxt = $localize`Hour`;
  minuteTxt = $localize`Minute`;
  rulTxt = $localize`Random uppercase letter`;
  rllTxt = $localize`Random lowercase letter`;
  rnTxt = $localize`Random number (between 0 and 9)`;
  staffNotificationsSettings = this.departmentForm.controls.staff_ticket_notifications_settings as UntypedFormArray;
  appBreakpointSubscription: Subscription;
  appBreakpoint: string;

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

  addTicketIdShortKey(key: string) {
    const currentIdFormat = this.departmentForm.controls.ticket_id_format.value;
    const newIdFormat = currentIdFormat + key;
    this.departmentForm.controls.ticket_id_format.setValue(newIdFormat);
  }

  ngOnInit() {
    super.ngOnInit();
    this.createOptions = this.activatedRoute.snapshot.data.createOptions;
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveDepartment();
    }
    if (this.object && this.object.id) {
      this.departmentForm.patchValue(this.object);
      if (this.object.staff_ticket_notifications_settings) {
        this.object.staff_ticket_notifications_settings.forEach(value => {
          this.staffNotificationsSettings.push(this.formBuilder.group(value));
        });
      }
    } else {
      if (this.createOptions) {
        this.departmentForm.controls.ticket_id_format.setValue(this.createOptions.ticket_id_default_format);
        this.createOptions.staff_users.forEach(user => {
          const setting = {
            user_display: user.full_name || user.email,
            user_id: user.id,
            ticket_open: true,
            staff_reply: true,
            enduser_reply: true,
            ticket_close: true,
          };
          this.staffNotificationsSettings.push(this.formBuilder.group(setting));
        });
      }
    }

    if (this.config?.appBreakpointObservable) {
      this.appBreakpointSubscription = this.config.appBreakpointObservable.subscribe(breakpoint => {
        this.appBreakpoint = breakpoint;
      });
    }
  }

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

    this.createOrUpdate(this.ticketDepartmentsApiService, value).subscribe(() => {
      this.router.navigateByUrl(
        this.config.getPrevUrl('tickets/departments')
      ).catch(() => {
      });
    });

    return of(null);
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    if (this.appBreakpointSubscription) {
      this.appBreakpointSubscription.unsubscribe();
      this.appBreakpointSubscription = null;
    }
  }

}
