import { Component, ViewChild } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IDomainModel } from '@fleio-api/plugins/domains/model/domain.model';
import { DomainApiService } from '@fleio-api/plugins/domains/domain-api.service';
import { IDomainWhoisFields } from '@fleio-api/plugins/domains/model/domain-whois-fields.model';
import { CustomFieldsComponent } from '@shared/fleio-data-controls/custom-fields/custom-fields.component';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
    selector: 'app-domain-details-whois-information',
    templateUrl: './domain-details-whois-information.component.html',
    styleUrls: ['./domain-details-whois-information.component.scss']
})
export class DomainDetailsWhoisInformationComponent extends DetailsComponentBase<IDomainModel> {
    @ViewChild('customFields') customFields: CustomFieldsComponent;
    whoisFields: IDomainWhoisFields;
    backendErrors: any = [];
    loadingWhois = false;

    constructor(
        private domainAPI: DomainApiService,
        private notificationService: NotificationService,
    ) {
        super();
    }

    protected tabActivated() {
        super.tabActivated();
        if (this.object?.id) {
            this.loadingWhois = true;
            this.domainAPI.getWhoisFields(this.object.id).subscribe({
                next: (whoisFields) => {
                    this.whoisFields = whoisFields;
                }, error: error => {
                    if (error?.error?.detail) {
                        this.notificationService.showMessage(error.error.detail);
                    }
                }
            }).add(() => {
                this.loadingWhois = false;
            });
        }
    }

    saveWhoisInformation() {
        const customFieldsValid = this.customFields.checkCustomFieldsForm();
        if (!customFieldsValid) {
            return;
        }

        if (this.customFields.customFieldsToSubmit && this.customFields.customFieldsToSubmit.length) {
            const customFields = this.customFields.customFieldsToSubmit;
            if (!customFields) {
                return;
            }
            this.objectController.loading = true;
            this.domainAPI.saveWhoisData(
                this.object.id,
                {
                    custom_fields: customFields,
                }
            ).subscribe({
                next: () => {
                    this.notificationService.showMessage($localize`Whois information updated.`);
                }, error: error => {
                    this.customFields.setBackendErrors(error.error);
                    this.notificationService.showMessage($localize`Failed to update whois information, please contact support.`);
                }
            }).add(() => {
                this.objectController.loading = false;
            });
        }
    }
}
