import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IContainerModel } from '@fleio-api/openstack/object-store/model/container.model';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { ContainersApiService } from '@fleio-api/openstack/object-store/containers/containers-api.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { EMPTY, Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ObjectsApiService } from '@fleio-api/openstack/object-store/objects/objects-api.service';
import { catchError } from 'rxjs/operators';
import { IAccountCapabilitiesModel } from '@fleio-api/openstack/object-store/model/account-capabilities.model';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-container-create-folder-form',
  templateUrl: './container-folder-create-form.component.html',
  styleUrls: ['./container-folder-create-form.component.scss']
})
export class ContainerFolderCreateFormComponent extends DetailsFormBase<IContainerModel> implements OnInit {
  folderForm: UntypedFormGroup;
  path: string;
  maxObjectNameLength = 1024;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private containersApiService: ContainersApiService,
    private router: Router,
    private config: ConfigService,
    private objectApi: ObjectsApiService,
    private activatedRoute: ActivatedRoute,
    private notificationService: NotificationService,
  ) {
    super();
  }

  createFolderForm(): UntypedFormGroup {
    return this.formBuilder.group({
      name: ['', [Validators.required, Validators.maxLength(this.maxObjectNameLength)]],
    });
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.containerActions();
      const capabilities: IAccountCapabilitiesModel = this.objectController.additionalObjects?.capabilities;
      if (capabilities) {
        this.maxObjectNameLength = capabilities.swift.max_object_name_length ||
          capabilities.swift.max_object_name_size || 1024;
      }
    }

    this.folderForm = this.createFolderForm();

    if (this.object) {
      const additionalQueryParams = Object.assign(
        {}, {container: this.object.id}, this.activatedRoute.snapshot.queryParams,
      );
      this.objectApi.setAdditionalQueryParams(additionalQueryParams);
    }

    this.path = this.activatedRoute.snapshot.queryParams?.path || '';
  }

  containerActions(): Observable<IActionResult> {
    const folder = this.folderForm.value;
    folder.path = this.path;

    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }

    let request = this.objectApi.create(folder);

    request = request.pipe(catchError((error) => {
      if (error.error) {
        this.setErrors(error.error);
        return EMPTY;
      } else {
        throw error;
      }
    }));


    this.objectController.loading = true;
    request.subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Folder created`);
        this.router.navigate(
          [this.config.getPanelUrl(`openstack/object-store/${this.object.id}`)],
          {queryParamsHandling: 'merge'},
        ).catch(() => {
        });
      },
      error: (error) => {
        this.objectController.loading = false;
        if (error.error) {
          this.setErrors(error.error);
        }
      }
    });

    return of(null);
  }
}
