import { Component, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { RouterHandler } from 'src/app/shared/services/router-handler.service';

@Component({
  selector: 'app-drive-window',
  templateUrl: './drive-window.component.html',
  styleUrls: ['./drive-window.component.scss'],
})
export class DriveWindowComponent implements OnDestroy {
  public resourceId;
  public routeSubscription;
  public paths = [];

  public onRouterChange = (res) => {
    if (this.resourceId !== res.params.id) {
      this.resourceId = res.params.id;
    }

    if (res.fragment?.path) {
      this.paths = res.fragment?.path.split('||');
    } else {
      this.paths = [''];
    }
  };

  constructor(private router: ActivatedRoute, private routerHandler: RouterHandler) {
    this.routerHandler.subscribe('room/?/drive', this.onRouterChange);
    if (this.routerHandler.isOnPage('room/?/drive')) {
      this.onRouterChange(this.routerHandler.getRoute());
    }
  }

  ngOnDestroy() {
    this.routerHandler.unsubscribe('room/?/drive', this.onRouterChange);
  }

  public renavigate(index, event) {
    const { path, from } = event;
    this.paths[index] = path;

    let fragment = this.routerHandler.getRoute().fragment;
    fragment['path'] = this.paths.join('||');
    delete fragment['file'];
    delete fragment['from'];
    if (from) {
      fragment['from'] = from;
    }

    this.routerHandler.navigate([], {
      relativeTo: this.router,
      fragment: this.routerHandler.fragmentToRaw(fragment),
    });
  }
}
