import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from '@angular/core';
import { OperationsApiService } from '@fleio-api/utils/operations/operations-api.service';
import { AuthService } from '@shared/auth/auth.service';
import { RefreshTimer } from '@shared/ui-api/helpers/refresh-timer';
import { ConfigService } from '@shared/config/config.service';
import { OrderingService } from '@shared/ui-api/ordering.service';
import { Subscription } from 'rxjs';
import { NotificationService } from '@shared/ui-api/notification.service';
import { Params } from '@angular/router';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { AppColor } from '@shared/ui/common/enums/app-color.enum';

@Component({
  selector: 'app-operations-in-progress',
  templateUrl: './operations-in-progress.component.html',
  styleUrls: ['./operations-in-progress.component.scss']
})
export class OperationsInProgressComponent implements OnInit, OnDestroy {
  private refreshTimer: RefreshTimer;
  private operationsCount: number;
  public hasOperationsInProgress = false;
  public hasUnseenFailedOperations = false;
  public operationsTooltip = '';
  hasInProgressOperationsSubscription: Subscription;
  failedOpIcon = {
    name: 'warning',
    color: AppColor.Yellow,
    tooltip: $localize`Failed operations exist`,
    tooltipDirection: 'down',
  } as IIcon;

  constructor(private operationsApiService: OperationsApiService, private authService: AuthService,
              private notificationService: NotificationService, public configService: ConfigService,
              public orderingService: OrderingService, private ngZone: NgZone,
              private changeDetectorRef: ChangeDetectorRef,) {
  }

  refresh() {
    if (this.authService?.userData?.user && this.authService.feature('utils.operations')) {
      this.hasInProgressOperationsSubscription = this.operationsApiService.hasOperationsInProgress()
        .subscribe(value => {
          this.hasOperationsInProgress = value.has_operations_in_progress;
          this.hasUnseenFailedOperations = value.unseen_failed_operations;
          this.operationsCount = value.operations_count;
          if (this.operationsCount) {
            this.operationsTooltip = this.operationsCount === 1 ? $localize`${this.operationsCount} operation in progress` :
              $localize`${this.operationsCount} operations in progress`;
            if (this.hasUnseenFailedOperations) {
              this.operationsTooltip += '\n';
              this.operationsTooltip += $localize`Failed operations exist`;
            }
          } else {
            this.operationsTooltip = '';
          }
        });
    }
  }

  ngOnInit(): void {
    this.refresh();
    if (this.configService?.current?.settings?.refreshIntervals) {
      this.refreshTimer = new RefreshTimer(
        this.configService.current.settings.refreshIntervals.operationsInProgressInterval, () => {
          this.refresh();
        }, this.configService, this.ngZone, this.changeDetectorRef, true
      );
    }
  }

  getRouterLink(): string {
    return this.configService.getPanelUrl('utilities/operations');
  }

  getQueryParams(): Params {
    let queryParams = this.orderingService.getQueryParams('utilities/operations');
    if (!queryParams) {
      queryParams = {};
    }
    if (this.hasUnseenFailedOperations) {
      if (!queryParams.hasOwnProperty('filtering')) {
        queryParams.filtering = `seen_by_users__ne:${this.authService.userData.user.id}+status:failed`;
      }
    } else {
      if (queryParams.hasOwnProperty('filtering')) {
        delete queryParams.filtering;
      }
    }
    return queryParams;
  }

  ngOnDestroy() {
    if (this.refreshTimer) {
      this.refreshTimer.stop();
      delete this.refreshTimer;
    }
    if (this.hasInProgressOperationsSubscription) {
      this.hasInProgressOperationsSubscription.unsubscribe();
      this.hasInProgressOperationsSubscription = null;
    }
  }
}
