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';
import { RefreshService } from '@shared/ui-api/refresh.service';

@Component({
  selector: 'app-tld-pricing',
  templateUrl: './tld-pricing.component.html',
  styleUrls: ['./tld-pricing.component.scss']
})
export class TldPricingComponent extends DetailsComponentBase<ITLDModel> implements OnInit {
  prices: ITLDPricesModel;
  domainPrices: IDomainPricesModel;
  currencies: string[];
  priceTypes = ['register', 'transfer', 'renew'];
  defaultPriceCycles: { [priceType: string]: number };
  transferAddsYearsTooltip = $localize`Some TLDs are transferred at no cost, and, during a transfer,\nyears are not added to the registration period.\nUncheck this for TLDs that are transferred for free.`;

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

  ngOnInit() {
    super.ngOnInit();
    this.initPrices();
  }

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

  checkAndSavePrices(event?: SubmitEvent) {
    const errors: string[] = [];

    // first, check that every currency has at least one price set for transfer, disallow save otherwise
    let minimumTransferPricesSet = true;
    for (const price of this.prices.domain_prices.price_cycles_list) {
      if (price.price_type === 'transfer') {
        let transferHasAtLeastOnePriceDefined = false;
        if (this.domainPrices.transfer_adds_years) {
          for (const amount of price.prices_per_years) {
            if (typeof amount === 'number') {
              transferHasAtLeastOnePriceDefined = true;
              break;
            }
          }
        } else {
          transferHasAtLeastOnePriceDefined = typeof price.prices_per_years[0] === 'number';
        }
        if (!transferHasAtLeastOnePriceDefined) {
          if (!this.domainPrices.transfer_adds_years) {
            errors.push($localize`Transfer price for ${price.currency.code} currency must be set!`);
            minimumTransferPricesSet = false;
          }
        }
      }
    }
    if (minimumTransferPricesSet) {
      // further checks
      for (const price of this.prices.domain_prices.price_cycles_list) {
        if (!price.relative_prices) {
          if (PriceValidator.hasNegativePrices(price)) {
            // do not accept negative prices
            return;
          }
          errors.push.apply(errors, PriceValidator.validatePrices(price, this.domainPrices.transfer_adds_years));
        }
      }
    }
    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`,
        yesButtonDisabled: !minimumTransferPricesSet,
        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 prices saved successfully`);
        this.refreshService.refresh(() => {
          this.initPrices();
        });
      },
      error: () => {
        this.notificationService.showMessage($localize`Failed to save TLD prices`);
      },
    }).add(() => {
      this.objectController.loading = false;
    });
  }
}
