/*
    $Id$
 */

// Suppliers en customer synchronizeren

// Generieke Sync-functie
// De code heeft af en toe nog 'SuppCust' als variabelenamen omdat de
// code eerst specifiek voor SuppCusts is begonnen
function SyncAnyTable(params)
{
    // Unit4 suppcusts lijst ophalen
    var suppcust = unit4.apiUnit4("GET", "/api/" + database + "/" + params.apiU4List + ".json");
    __Log("Found " + suppcust.length + " unit4 " + params.apiU4Record);
    //WScript.Echo(JSON.stringify(usupl, null, '  '));
    // Even omzetten naar een handiger formaat
    var SuppCusts = {};
    for (var i in suppcust)
    {
        SuppCusts[suppcust[i][params.apiU4ListKey]] = { Existing: 1 };
    }

    // FACILITOR suppcusts lijst ophalen
    var fcltSuppCusts = params.FCLTData;
    if (!fcltSuppCusts || fcltSuppCusts.length < params.mincnt)
    {
        __Log("ERROR ABORTING: Not enough Facilitor records for " + params.apiU4List);
        __Log("Expected " + params.mincnt + " got: " + fcltSuppCusts.length);
        WScript.Quit();
    }
    __Log("Found " + fcltSuppCusts.length + " FACILITOR records");

    var cnt = 0;
    for (var s in fcltSuppCusts)
    {
        cnt++;
        if (params.limit && cnt > params.limit)
        {
            WScript.Echo("Limit reached, stopping after " + params.limit);
            break;
        }
        var suppdata = fcltSuppCusts[s];
        var SuppCustId = suppdata[params.SuppCustIdName];
        if (SuppCusts[SuppCustId])
        {   // Bestaande data ophalen
            var method = "PUT";
            var url = "/api/" + database + "/" + params.apiU4Record + "/" + SuppCustId + ".json";
            var SuppCustData = unit4.apiUnit4("GET", url);
        }
        else
        {
            method = "POST";
            var url = "/api/" + database + "/" + params.apiU4Record + ".json";
            SuppCusts[SuppCustId] = { SuppCustId : SuppCustId }; // zodadelijk is hij er
            var SuppCustData = { SuppCustId : SuppCustId };
        }
        var NewSuppCustData = params.fnNewData(suppdata);
        for (var i in NewSuppCustData)
            SuppCustData[i] = NewSuppCustData[i];

        //WScript.Echo("About to " + method + "\n" + JSON.stringify(SuppCustData, null, '  '));
        WScript.Echo(cnt + " About to " + method + " " + SuppCustId + ": " + suppdata.NAME);

        var jresp = unit4.apiUnit4(method, url, SuppCustData);
        SuppCusts[SuppCustId].OrganizationId = jresp.OrganizationId; // Deze onthouden
        WScript.Echo("\tOrganizationId: " + jresp.OrganizationId);
    }
    // Nu bevat Array SuppCusts ook de OrganizationId van iedere SuppCustId
    //WScript.Echo(JSON.stringify(SuppCusts, null, '  '));
    return SuppCusts;
}

// ======================================
// ============== SUPPLIER ==============
// ======================================
// Het resultaat is een json-hash waarbij van elke Supplier-ID
// ook de OrganizationId wordt bijgehouden.
function SyncSuppliers()
{
    var params = {
                   xlimit: 5, // testing
                   mincnt: config.mincntSupplier,
                   apiU4List: "SupplierNVL",
                   apiU4ListKey: "Name",
                   apiU4Record: "Supplier",
                   FCLTData: apiFACILITOR("UNIT4", "<GetSuppliers/>").supplier,
                   SuppCustIdName: "SUPPLIERID",
                   fnNewData: function (suppdata) {
                                return { SupplierId         : suppdata.SUPPLIERID,
                                         City               : suppdata.CITY,
                                         CoRegistration     : suppdata.COREGISTRATION,
                                         CombineInvoicesForElectronicBanking : suppdata.COMBINEINVOICES,
                                         Email              : suppdata.EMAIL,
                                         Fax                : suppdata.FAX,
                                         Name               : suppdata.NAME.substr(0, 40),
                                         PaymentConditionId : suppdata.PAYMENTCONDITIONID,
                                         Person             : suppdata.PERSON,
                                         ZipCode            : suppdata.ZIPCODE,
                                         ShortName          : suppdata.SHORTNAME,
                                         Street1            : suppdata.STREET1,
                                         Street2            : suppdata.STREET2,
                                         SupplierGroupId    : suppdata.SUPPLIERGROUPID,
                                         Telephone          : suppdata.TELEPHONE,
                                         VatNumber          : suppdata.VATNUMBER
                                       }
                                    }
                 };
    return SyncAnyTable(params);
}

// ======================================
// ============== CUSTOMER ==============
// ======================================
// Het resultaat is een json-hash waarbij van elke Customer-ID
// ook de OrganizationId wordt bijgehouden.
function SyncCustomers()
{
    var params = {
                   xlimit: 5, // testing
                   mincnt: config.mincntCustomer,
                   apiU4List: "CustomerNVL",
                   apiU4ListKey: "Name",
                   apiU4Record: "Customer",
                   FCLTData: apiFACILITOR("UNIT4", "<GetCustomers/>").customer,
                   SuppCustIdName: "CUSTOMERID",
                   fnNewData: function (custdata) {
                                return { CustomerId         : custdata.CUSTOMERID,
                                         ChargeVatTypeId    : custdata.CHARGEVATTYPEID,
                                         City               : custdata.CITY,
                                         CocRegistration    : custdata.COCREGISTRATION,
                                         CreditSqueezeId    : custdata.CREDITSQUEEZEID,
                                         CustomerGroupId    : custdata.CUSTOMERGROUPID,
                                         Email              : custdata.EMAIL,
                                         Fax                : custdata.FAX,
                                         Name               : custdata.NAME.substr(0, 40),
                                         PaymentConditionId : custdata.PAYMENTCONDITIONID,
                                         Person             : custdata.PERSON,
                                         ZipCode            : custdata.ZIPCODE,
                                         ShortName          : custdata.SHORTNAME,
                                         Street1            : custdata.STREET1,
                                         Street2            : custdata.STREET2,
                                         Telephone          : custdata.TELEPHONE
                                       }
                                   }
                 };
    return SyncAnyTable(params);
}
