import { Component, Input, OnChanges, OnDestroy, OnInit } from '@angular/core';
import { CordovaService } from 'src/app/shared/services/cordova.service';
import { NanoService } from 'src/app/shared/nano/nano.service';
import { RoomService } from 'src/app/shared/server-services/room.service';
import { RoomRecord } from 'src/app/shared/server-services/query-records/room-records';
import {
  CollectionManagerType,
  CollectionObject,
  DownloadManagerService,
  FileManagerDirection,
} from 'src/app/shared/services/download-manager-service';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { DialogService } from 'src/app/shared/services/dialog.service';
import { RouterHandler } from 'src/app/shared/services/router-handler.service';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
import { scrollToFileObserver } from '../../resource-page/drive-window/drive-layout/drive-layout.component';

@Component({
  selector: 'app-download-manager-collection',
  templateUrl: './download-manager-collection.component.html',
  styleUrls: [
    './download-manager-collection.component.scss',
    './download-manager-collection-mat.component.scss',
  ],
})
export class DownloadManagerCollectionComponent implements OnInit, OnChanges, OnDestroy {
  @Input() collection: CollectionManagerType;

  public roomData: RoomRecord;
  public isOpen = false;

  public sumRawTimeNeeded: string = '';
  public sumSpeed = 0;

  private timeUpdater = null;

  constructor(
    private cordovaService: CordovaService,
    private dialogService: DialogService,
    private downloadManagerService: DownloadManagerService,
    private nanoService: NanoService,
    private roomService: RoomService,
    private routerHandler: RouterHandler,

    private bottomSheet: MatBottomSheet
  ) {}

  ngOnInit(): void {
    this.roomService.getRoom(this.collection.resourceId).then((data) => {
      this.roomData = data;
    });

    this.timeUpdater = setInterval(() => {
      if (this.collection && !this.collection.done && !this.collection.isPaused) {
        console.log('update on ', this.collection.collectionId);
        this.calcTimeAndSpeed();
      }
    }, 1000);
  }

  ngOnDestroy(): void {
    clearInterval(this.timeUpdater);
  }

  ngOnChanges(changes: any): void {
    console.log('changes', changes);
  }

  public calcTimeAndSpeed = () => {
    if (this.collection && this.collection?.inProgressParts?.length > 0) {
      let speed = 0;
      for (const onePart of this.collection.inProgressParts) {
        if (onePart.status === 'inprogress') {
          if (onePart.speed) {
            speed += onePart.speed;
          }
        }
      }
      this.sumSpeed = speed;
      if (speed) {
        this.sumRawTimeNeeded = this.humanizeTime(
          (this.collection.maxSize * (100 - this.collection.progress)) / 100 / speed
        );
      }
    }
  };

  openDetails = () => {
    this.isOpen = true;
  };
  closeDetails = () => {
    this.isOpen = false;
  };

  private humanizeTime(timeNeeded: number): string {
    function pad(n) {
      return n < 10 ? '0' + n : n;
    }

    var h = Math.floor(timeNeeded / 3600);
    var m = Math.floor(timeNeeded / 60) - h * 60;
    var s = Math.floor(timeNeeded - h * 3600 - m * 60);

    if (h > 0) {
      return pad(h) + ':' + pad(m) + ':' + pad(s);
    } else if (m > 0) {
      return m + ':' + pad(s);
    } else {
      return s + ' sec';
    }
  }

  public pause() {
    console.log('is paused: ', this.collection.isPaused);
    this.downloadManagerService.pauseCollection(this.collection);
  }

  public resume() {
    if (this.collection.isPaused) {
      this.collection.isPaused = false;

      this.downloadManagerService.resumeCollection(this.collection);
    }
  }

  public resumeWithError() {
    this.downloadManagerService.resumeCollectionWithError(this.collection);
  }

  public remove() {
    this.dialogService
      .openConfirmDialog(
        marker('Remove downloading file'),
        marker('Are you sure you want to stop the file progress?') +
          '( ' +
          this.collection.path +
          ' )'
      )
      .subscribe((response) => {
        if (response) {
          this.downloadManagerService.removeCollection(this.collection);
        }
      });
  }

  public openPath(part?: CollectionObject) {
    if (this.isUploading) return;

    let fragment = this.routerHandler.getRoute().fragment;
    if (part) {
      fragment['path'] = part.path.split('/').slice(0, -1).join('/');
      fragment['file'] = part.file.name;
    } else {
      fragment['path'] = this.collection.path.split('/').slice(0, -1).join('/');
      fragment['file'] = this.collection.path.split('/').slice(-1)[0];
    }

    if (fragment?.['from']) {
      delete fragment['from'];
    }
    this.routerHandler.navigate(['/room/', this.collection.resourceId, 'drive'], {
      fragment: this.routerHandler.fragmentToRaw(fragment),
    });
    if (fragment['file']) {
      scrollToFileObserver.next(fragment['file']);
    }

    this.bottomSheet.dismiss();
  }

  get isUploading(): boolean {
    return !this.collection.done && this.collection.direction == 'up';
  }
}
