//---------------------------------------------------------------------------------------------
// 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 { SpecialOfferProduct_ReadListOutput, ISpecialOfferProductService } from 'ServiceContracts/Sales/ISpecialOfferProductService';
import { LocalLookupCacheLoader, fromJSON, Header, LookupTable, ErrorList } from 'xomega';

export class SpecialOfferProductReadListCacheLoader extends LocalLookupCacheLoader {

    constructor() {
        super(true, 'special offer product');
    }

    protected getLoadRequest(): JQueryAjaxSettings {
        var _productId = this.parameters['product id'];
        if (_productId == null) return null;
        return ISpecialOfferProductService.getReadListAsyncRequest(_productId);
    }

    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 SpecialOfferProduct_ReadListOutput();
                fromJSON(row, r);
                let h: Header = lkpData[row.SpecialOfferId] || new Header(tableType, row.SpecialOfferId, row.Description);
                h.isActive = row.Active;
                h.addToAttribute('discount', row.Discount);
                h.addToAttribute('min qty', row.MinQty);
                h.addToAttribute('max qty', row.MaxQty);
                lkpData[row.SpecialOfferId] = 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);
    }
}