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 { ITLDPricesModel } from '@fleio-api/plugins/domains/model/tld-prices.model';
import { IDomainPricesModel } from '@fleio-api/plugins/domains/model/domain-prices.model';
import { TLDsApiService } from '@fleio-api/plugins/domains/tlds-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';
import { PriceValidator } from '../../price-validator';

@Component({
  selector: 'app-tld-addons-pricing',
  templateUrl: './tld-addons-pricing.component.html',
  styleUrls: ['./tld-addons-pricing.component.scss']
})
export class TldAddonsPricingComponent extends DetailsComponentBase<ITLDModel> implements OnInit {
  prices: ITLDPricesModel;
  addonsPrices: IDomainPricesModel;
  currencies: string[];
  priceTypes = ['dns', 'email', 'id'];
  defaultPriceCycles: { [priceType: string]: number };

  constructor(
    private tldsApiService: TLDsApiService,
    private notificationService: NotificationService,
    public config: ConfigService
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.prices = this.objectController.additionalObjects.prices as ITLDPricesModel;
      this.prices = JSON.parse(JSON.stringify(this.prices));
      this.addonsPrices = this.prices.domain_addon_prices;
      // get a list of currencies ensuring default currency is first
      this.currencies = Object.keys(this.addonsPrices.price_cycles_by_currency).filter(
        currencyCode => currencyCode !== this.addonsPrices.default_currency.code,
      );
      this.currencies.unshift(this.addonsPrices.default_currency.code);
      this.defaultPriceCycles = this.addonsPrices.price_cycles_by_currency[this.addonsPrices.default_currency.code];
    }
  }


  checkAndSavePrices() {
    const errors: string[] = [];
    for (const price of this.prices.domain_addon_prices.price_cycles_list) {
      errors.push.apply(errors, PriceValidator.validatePrices(price));
    }
    if (errors.length) {
      this.notificationService.confirmDialog({
        title: $localize`Invalid prices detected`,
        message: $localize`The following problems were encountered when checking prices:`,
        importantMessage: errors.join('\n'),
        yesButtonName: $localize`Save anyway`,
        noButtonName: $localize`Cancel`,
      }).subscribe((result) => {
        if (result?.button === 'yes') {
          this.savePrices();
        }
      });
    } else {
      this.savePrices();
    }
  }


  savePrices() {
    this.objectController.loading = true;
    this.tldsApiService.savePrices(this.object.id, this.prices).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`TLD addons prices saved successfully`);
      },
      error:() => {
        this.notificationService.showMessage($localize`Failed to save TLD addons prices`);
      },
    }).add(() => {
      this.objectController.loading = false;
    });
  }
}
