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 { ObjectsApiService } from '@fleio-api/openstack/object-store/objects/objects-api.service';
import { EMPTY, Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { catchError } from 'rxjs/operators';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IAccountCapabilitiesModel } from '@fleio-api/openstack/object-store/model/account-capabilities.model';

@Component({
  selector: 'app-container-object-copy-form',
  templateUrl: './container-object-copy-form.component.html',
  styleUrls: ['./container-object-copy-form.component.scss']
})
export class ContainerObjectCopyFormComponent extends DetailsFormBase<IContainerModel> implements OnInit {
  copyForm: UntypedFormGroup;
  fileId: string;
  public containers: IContainerModel[];
  maxContainerNameLength = 255;
  maxObjectNameLength = 1024;
  containerOptionsSwitchMap: (search: string) => Observable<any>;
  containerSelectedPlaceholder = $localize`Destination container`;
  containerUnselectedPlaceholder = $localize`Select destination container ...`;

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

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

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

    this.copyForm = this.createCopyForm();

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

    this.fileId = this.activatedRoute.snapshot.queryParams?.fileId || '';

    this.containerOptionsSwitchMap = (search) => {
      const lowerCaseValue = search.toLocaleLowerCase();
      return of(this.containers.filter(
        container => container.name.toLocaleLowerCase().includes(lowerCaseValue)
      ));
    };
  }

  containerActions(): Observable<IActionResult> {
    const copyData = this.copyForm.value;
    copyData.container = copyData.container.name;

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

    const destination = copyData.container + '/' + copyData.name;

    let request = this.objectApi.copy(this.fileId, destination);

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

    this.objectController.loading = true;
    request.subscribe(() => {
      this.notificationService.showMessage($localize`File copied`);
      this.router.navigate(
        [this.config.getPanelUrl(`openstack/object-store/${copyData.container}`)],
        {queryParamsHandling: 'merge', queryParams: {fileId: undefined}},
      ).then(() => {
      });
    }, error => {
      this.objectController.loading = false;
      if (error.error) {
        this.setErrors(error.error);
      }
    });

    return of(null);
  }
}
