//---------------------------------------------------------------------------------------------
// This file was AUTO-GENERATED by "TS Lookup Cache Loaders" Xomega.Net generator.
//
// Manual CHANGES to this file WILL BE LOST when the code is regenerated.
//---------------------------------------------------------------------------------------------

import { BusinessEntityAddress_ReadListOutput, IBusinessEntityAddressService } from 'ServiceContracts/Person/IBusinessEntityAddressService';
import { LocalLookupCacheLoader, fromJSON, Header, LookupTable, ErrorList } from 'xomega';

export class BusinessEntityAddressReadListCacheLoader extends LocalLookupCacheLoader {

    constructor() {
        super(true, 'business entity address');
    }

    protected getLoadRequest(): JQueryAjaxSettings {
        var _businessEntityId = this.parameters['business entity id'];
        if (_businessEntityId == null) return null;
        return IBusinessEntityAddressService.getReadListAsyncRequest(_businessEntityId);
    }

    public loadCache(tableType: string, updateCache: (table: LookupTable) => void) {
        let req: JQueryAjaxSettings = this.getLoadRequest();
        if (req == null) return;
        let cl = this;
        req.success = function (data) {
            let lkpData: { [key: string]: Header } = {};
            let rows = data.result || data.Result || [];
            for (let r of rows) {
                let row = new BusinessEntityAddress_ReadListOutput();
                fromJSON(row, r);
                let h: Header = lkpData[row.AddressId] || new Header(tableType, row.AddressId, row.AddressType);
                h.addToAttribute('address line1', row.AddressLine1);
                h.addToAttribute('address line2', row.AddressLine2);
                h.addToAttribute('city', row.City);
                h.addToAttribute('state', row.State);
                h.addToAttribute('postal code', row.PostalCode);
                h.addToAttribute('country', row.Country);
                lkpData[row.AddressId] = h;
            }
            var tblData = Object.keys(lkpData).map(k => lkpData[k]);
            var tbl: LookupTable = new LookupTable(tableType, tblData, cl.caseSensitive);
            updateCache(tbl);
        };
        req.error = (jqXHR, textStatus, errorThrow) => {
            updateCache(LookupTable.fromErrors(tableType, ErrorList.fromErrorResponse(jqXHR, errorThrow)));
        };
        $.ajax(req);
    }
}