import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';
import { BackupSchedulesApiService } from '@fleio-api/openstack/backups/backup-schedules-api.service';
import { AuthService } from '@shared/auth/auth.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { DBaaSBackupSchedulesApiService } from '@fleio-api/openstack/dbaas/dbaas-backup-schedules-api.service';

@Component({
  selector: 'app-create-dbaas-backup-schedule-dialog',
  templateUrl: './create-dbaas-backup-schedule-dialog.component.html',
  styleUrl: './create-dbaas-backup-schedule-dialog.component.scss'
})
export class CreateDbaasBackupScheduleDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  loading = false;
  backupScheduleForm = this.initForm();
  dialogTitle = $localize`Create backup schedule for database instance ${this.data.database_instance.name || this.data.database_instance.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Create backup schedule`,
      primary: true,
      callback: () => this.createSchedule(),
    }),
  ];
  dialogForm = this.backupScheduleForm;
  hourChoices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
  daysChoices = [0, 1, 2, 3, 4, 5, 6];
  backupType = this.backupScheduleForm.controls.backup_type;
  dayControl = this.backupScheduleForm.controls.day;
  public incrementalInfo: IIcon = {
    name: 'info',
    verticalAlign: 'middle',
    fontSize: '20px',
    marginLeft: '5px',
    marginTop: '2px',
    tooltip: $localize`Creates incremental backups based on the last full backup.`
  };

  initForm() {
    if (this.data && this.data.database_instance) {
      return this.formBuilder.group({
        database_instance: [this.data.database_instance.id],
        backup_name: ['', Validators.required],
        backup_type: ['daily', Validators.required],
        hour: [0, ValidatorsHelper.requiredIntegerValidator],
        day: [1, ValidatorsHelper.requiredIntegerValidator],
        swift_container: [null],
        incremental: [false],
        run_at: [null],
      });
    }
    return this.formBuilder.group({
      database_instance: [''],
      backup_name: ['', Validators.required],
      backup_type: ['daily', Validators.required],
      hour: [0, ValidatorsHelper.requiredIntegerValidator],
      day: [1, ValidatorsHelper.requiredIntegerValidator],
      swift_container: [null],
      incremental: [false],
      run_at: [null],
    });
  }

  constructor(
    private formBuilder: UntypedFormBuilder,
    private dbaasBackupSchedulesApiService: DBaaSBackupSchedulesApiService,
    public auth: AuthService,
    public dialogRef: MatDialogRef<CreateDbaasBackupScheduleDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      database_instance: IDbaasInstanceModel;
    },
  ) { }

  dayOfWeekAsString(day: number) {
    return [$localize`Monday`, $localize`Tuesday`, $localize`Wednesday`, $localize`Thursday`,
      $localize`Friday`, $localize`Saturday`, $localize`Sunday`][day];
  }

  changedBackupType() {
    if (this.backupType.value === 'weekly') {
      this.dayControl.enable();
    } else {
      this.dayControl.disable();
    }
  }

  hourDisplay(hour: number) {
    if (hour < 10) {
      return '0' + hour + ':00';
    } else {
      return hour + ':00';
    }
  };

  public createSchedule() {
    this.loading = true;
    if (!this.backupScheduleForm.valid) {
      this.loading = false;
      return;
    }
    const value = this.backupScheduleForm.value;
    this.dbaasBackupSchedulesApiService.create(value).subscribe(response => {
      this.loading = false;
      this.dialogRef.close(true);
    }, error => {
      this.loading = false;
      this.formErrors.setBackendErrors(error.error);
    });
  }

  ngOnInit(): void {
    this.changedBackupType();
    if (!this.auth.feature('ui.openstack.instances.backup_schedules.select_hour')) {
      this.backupScheduleForm.removeControl('hour');
    }
  }

}
