var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { AbstractFieldWriteComponent } from '../base-field/abstract-field-write.component';
import { Component, Input, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { WriteComplexFieldComponent } from '../complex/write-complex-field.component';
import { AddressModel } from '../../../domain/addresses/address.model';
import { AddressOption } from './address-option.model';
import { AddressesService } from '../../../services/addresses/addresses.service';
import { FormControl, FormGroup } from '@angular/forms';
import { IsCompoundPipe } from '../utils/is-compound.pipe';
import { FocusElementDirective } from '../../../directives/focus-element';
var WriteAddressFieldComponent = /** @class */ (function (_super) {
    __extends(WriteAddressFieldComponent, _super);
    function WriteAddressFieldComponent(addressesService, isCompoundPipe) {
        var _this = _super.call(this) || this;
        _this.isCompoundPipe = isCompoundPipe;
        _this.addressFormGroup = new FormGroup({});
        _this.errDisplay = PostCodeLookupError;
        _this.addressesService = addressesService;
        return _this;
    }
    WriteAddressFieldComponent.prototype.ngOnInit = function () {
        if (!this.isComplexWithHiddenFields()) {
            this.postcode = new FormControl('');
            this.addressFormGroup.addControl('postcode', this.postcode);
            this.addressList = new FormControl('');
            this.addressFormGroup.addControl('address', this.addressList);
        }
    };
    WriteAddressFieldComponent.prototype.findAddress = function () {
        var _this = this;
        if (!this.postcode.value) {
            this.postcodeLookupError = PostCodeLookupError.MISSING_POSTCODE;
        }
        else {
            this.postcodeLookupError = undefined;
            var postcode_1 = this.postcode.value;
            this.caseField.value = null;
            this.addressOptions = new Array();
            this.addressesService.getAddressesForPostcode(postcode_1.replace(' ', '').toUpperCase()).subscribe(function (result) {
                result.forEach(function (address) {
                    _this.addressOptions.push(new AddressOption(address, null));
                });
                _this.addressOptions.unshift(new AddressOption(undefined, _this.defaultLabel(_this.addressOptions.length)));
            }, function (error) {
                if (error.status === 400) {
                    _this.postcodeLookupError = PostCodeLookupError.BAD_REQUEST;
                }
                else if (error.status === 429) {
                    _this.postcodeLookupError = PostCodeLookupError.TRIES_EXHAUSTED;
                }
                else if (error.status === 500) {
                    _this.postcodeLookupError = PostCodeLookupError.SERVICE_UNAVAILABLE;
                }
                console.log("An error occurred retrieving addresses for postcode " + postcode_1 + ". " + JSON.stringify(error));
                _this.addressOptions.unshift(new AddressOption(undefined, _this.defaultLabel(_this.addressOptions.length)));
            });
            this.addressList.setValue(undefined);
            this.refocusElement();
        }
    };
    WriteAddressFieldComponent.prototype.refocusElement = function () {
        if (this.focusElementDirectives && this.focusElementDirectives.length > 0) {
            this.focusElementDirectives.first.focus();
        }
    };
    WriteAddressFieldComponent.prototype.blankAddress = function () {
        this.caseField.value = new AddressModel();
        this.setFormValue();
    };
    WriteAddressFieldComponent.prototype.isComplexWithHiddenFields = function () {
        if (this.caseField.field_type.type === 'Complex' && this.caseField.field_type.complex_fields
            && this.caseField.field_type.complex_fields.some(function (cf) { return cf.hidden === true; })) {
            return true;
        }
    };
    WriteAddressFieldComponent.prototype.shouldShowDetailFields = function () {
        if (this.isComplexWithHiddenFields()) {
            return true;
        }
        if (this.isExpanded) {
            return true;
        }
        if (!this.writeComplexFieldComponent || !this.writeComplexFieldComponent.complexGroup) {
            return false;
        }
        var address = this.writeComplexFieldComponent.complexGroup.value;
        var hasAddress = false;
        if (address) {
            Object.keys(address).forEach(function (key) {
                if (address[key] != null) {
                    hasAddress = true;
                }
            });
        }
        return hasAddress;
    };
    WriteAddressFieldComponent.prototype.addressSelected = function () {
        this.caseField.value = this.addressList.value;
        this.setFormValue();
    };
    WriteAddressFieldComponent.prototype.ngOnChanges = function (changes) {
        if (changes['caseField']) {
            this.setFormValue();
        }
    };
    WriteAddressFieldComponent.prototype.createId = function (elementId) {
        return this.id() + '_' + elementId;
    };
    WriteAddressFieldComponent.prototype.defaultLabel = function (numberOfAddresses) {
        return numberOfAddresses === 0 ? 'No address found'
            : numberOfAddresses + (numberOfAddresses === 1 ? ' address ' : ' addresses ') + 'found';
    };
    WriteAddressFieldComponent.prototype.setFormValue = function () {
        if (this.writeComplexFieldComponent.complexGroup) {
            this.writeComplexFieldComponent.complexGroup.setValue(this.caseField.value);
        }
    };
    __decorate([
        ViewChild('writeComplexFieldComponent', { static: true }),
        __metadata("design:type", WriteComplexFieldComponent)
    ], WriteAddressFieldComponent.prototype, "writeComplexFieldComponent", void 0);
    __decorate([
        ViewChildren(FocusElementDirective),
        __metadata("design:type", QueryList)
    ], WriteAddressFieldComponent.prototype, "focusElementDirectives", void 0);
    __decorate([
        Input(),
        __metadata("design:type", FormGroup)
    ], WriteAddressFieldComponent.prototype, "formGroup", void 0);
    WriteAddressFieldComponent = __decorate([
        Component({
            selector: 'ccd-write-address-field',
            template: "\n    <div class=\"form-group\" [id]=\"id()\">\n\n      <div *ngIf=\"!isComplexWithHiddenFields()\">\n        <h2 class=\"heading-h2\">{{caseField | ccdFieldLabel }}</h2>\n\n        <div class=\"form-group bottom-30\" id=\"postcodeLookup\" [ngClass]=\"{'form-group-error': missingPostcode}\" *ngIf=\"!isExpanded\">\n          <label [for]=\"createId('postcodeInput')\">\n            <span class=\"form-label\">Enter a UK postcode</span>\n          </label>\n          <span class=\"error-message\" *ngIf=\"postcodeLookupError === errDisplay.MISSING_POSTCODE\">Enter the Postcode</span>\n          <span class=\"error-message\" *ngIf=\"postcodeLookupError === errDisplay.BAD_REQUEST\">Incorrect postcode data, please try again</span>\n          <span class=\"error-message\" *ngIf=\"postcodeLookupError === errDisplay.TRIES_EXHAUSTED\">Daily lookup quota exhausted, please fill in the address manually</span>\n          <span class=\"error-message\" *ngIf=\"postcodeLookupError === errDisplay.SERVICE_UNAVAILABLE\">Address look up service is unavailable, please fill in the address manually</span>\n          <input type=\"text\" [id]=\"createId('postcodeInput')\" name=\"postcode\" class=\"form-control postcodeinput\" [formControl]=\"postcode\">\n          <button type=\"button\" class=\"button button-30\" (click)=\"findAddress()\">Find address</button>\n        </div>\n\n        <div class=\"form-group\" *ngIf=\"addressOptions\" id=\"selectAddress\">\n          <label [for]=\"createId('addressList')\">\n            <span class=\"form-label\">Select an address</span>\n          </label>\n\n          <select class=\"form-control ccd-dropdown addressList\" [id]=\"createId('addressList')\" name=\"address\" [formControl]=\"addressList\" (change)=\"addressSelected()\" focusElement>\n            <option *ngFor=\"let addressOption of addressOptions\" [ngValue]=\"addressOption.value\">\n              {{addressOption.description}}\n            </option>\n          </select>\n        </div>\n\n        <a class=\"manual-link bottom-30\" *ngIf=\"!shouldShowDetailFields()\" (click)=\"blankAddress()\" href=\"javascript:void(0)\">I can't enter a UK postcode</a>\n      </div>\n\n      <ccd-write-complex-type-field\n        [hidden]=\"!shouldShowDetailFields()\"\n        [(caseField)]=\"caseField\"\n        [renderLabel]=\"false\"\n        [formGroup]=\"formGroup\"\n        [registerControl]=\"registerControl\"\n        [ignoreMandatory]=\"true\"\n        [idPrefix]=\"idPrefix\"\n        #writeComplexFieldComponent>\n      </ccd-write-complex-type-field>\n\n    </div>\n  ",
            styles: ["\n    .manual-link{cursor:pointer;display:block;text-decoration:underline}\n  "]
        }),
        __metadata("design:paramtypes", [AddressesService, IsCompoundPipe])
    ], WriteAddressFieldComponent);
    return WriteAddressFieldComponent;
}(AbstractFieldWriteComponent));
export { WriteAddressFieldComponent };
export var PostCodeLookupError;
(function (PostCodeLookupError) {
    PostCodeLookupError[PostCodeLookupError["MISSING_POSTCODE"] = 0] = "MISSING_POSTCODE";
    PostCodeLookupError[PostCodeLookupError["BAD_REQUEST"] = 1] = "BAD_REQUEST";
    PostCodeLookupError[PostCodeLookupError["SERVICE_UNAVAILABLE"] = 2] = "SERVICE_UNAVAILABLE";
    PostCodeLookupError[PostCodeLookupError["TRIES_EXHAUSTED"] = 3] = "TRIES_EXHAUSTED";
})(PostCodeLookupError || (PostCodeLookupError = {}));
//# sourceMappingURL=write-address-field.component.js.map