import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { IServiceModel, PriceOverrideModel } from '@fleio-api/billing/model/service.model';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { ConfigService } from '@shared/config/config.service';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-service-details-overview',
  templateUrl: './service-details-overview.component.html',
  styleUrls: ['./service-details-overview.component.scss']
})
export class ServiceDetailsOverviewComponent extends DetailsComponentBase<IServiceModel> implements OnInit {
  displayedColumns: string[] = ['option', 'option_value', 'unit_price', 'price'];
  showOrder: boolean;
  initialServerId: FleioId;
  PriceOverrideModel = PriceOverrideModel;

  constructor(
    public config: ConfigService,
    ngZone: NgZone,
    protected changeDetectorRef: ChangeDetectorRef,
    private servicesApiService: ServicesApiService,
    private refreshService: RefreshService,
    private notificationService: NotificationService,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  protected refreshData() {
    this.refreshService.refresh();
  }

  ngOnInit() {
    super.ngOnInit();

    if (this.object && this.object.hosting_account) {
      this.initialServerId = this.object.hosting_account.server;
    }
    this.showOrder = this.authSvc.feature('ui.billing.services.show-order');
  }

  get showUpgradeButtons() {
    return this.authSvc.feature(
      'ui.billing.services.upgrade-downgrade',
    ) && ['pending', 'active'].includes(
      this.object.status,
    ) && this.object.cycle.cycle !== 'onetime' && !this.object.resources.disabled_features.includes('upgrade');
  }

  updateServer() {
    this.servicesApiService.updateHostingAccount(
      this.object.id, this.object.hosting_account,
    ).subscribe({
        next:
          () => {
            this.notificationService.showMessage($localize`Server updated`);
            this.refreshService.refresh();
          },
        error: () => {
          this.notificationService.showMessage($localize`Failed to update server`);
        }
      }
    );
  }
}
