import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { ITLDModel } from '@fleio-api/plugins/domains/model/tld.model';
import { RegistrarConnectorApiService } from '@fleio-api/plugins/domains/registrar-connector-api.service';
import { IRegistrarConnectorModel } from '@fleio-api/plugins/domains/model/registrar-connector.model';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-tld-cost-pricing',
  templateUrl: './tld-cost-pricing.component.html',
  styleUrls: ['./tld-cost-pricing.component.scss']
})
export class TldCostPricingComponent extends DetailsComponentBase<ITLDModel> implements OnInit {
  registrarConnectors: IRegistrarConnectorModel[];

  constructor(
    private registrarConnectorApiService: RegistrarConnectorApiService,
    public config: ConfigService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();

    if (this.object) {
      this.registrarConnectorApiService.getRegistrarPrices(this.object.name).subscribe(prices => {
          this.registrarConnectors = prices;
        }
      );
    }
  }

  updateRegistrarPrices(registrarConnectorName: string) {
    this.objectController.loading = true;
    this.registrarConnectorApiService.updateRegistrarPrices(
      registrarConnectorName, this.object.name
    ).subscribe({
        next: () => {
          this.registrarConnectorApiService.getRegistrarPrices(this.object.name).subscribe(
            {
              next: prices => {
                this.registrarConnectors = prices;
              },
              error: error => {
                this.notificationService.showMessage(error.error.detail);
              }
            }
          );
        },
        error: error => {
          this.notificationService.showMessage(error.error.detail);
        }
      }
    ).add(() => {
      this.objectController.loading = false;
    });
  }
}
