/*
    $Id$
 */

// Banken synchronizeren

// Opvragen Rentokil: cscript Unit4Facilitor.wsf BankAccountInfoList/625.json
function SyncBankAccounts(Suppliers, Customers)
{
    var apiU4Record = "BankAccount";

    // FACILITOR Adressen lijst ophalen
    var fcltBanks = apiFACILITOR("UNIT4", "<GetBankAccounts/>").bankaccount;
    __Log("Found " + fcltBanks.length + " FACILITOR BankAccounts");
    ///WScript.Echo(JSON.stringify(fcltBank, null, '  '));

    for (var a in fcltBanks)
    {
        var bankdata = fcltBanks[a];
        var OurId = bankdata.SUPCUSID;
        var orgID = null;
        if (Customers[OurId])
        {
            orgID = Customers[OurId].OrganizationId;
        }
        else if (Suppliers[OurId])
        {
            orgID = Suppliers[OurId].OrganizationId;
        }

        if (!orgID)
        {
            __Log("ERROR: Bankaccount owner for " + OurId + " not found");
        }
        else
        {
            var newData = {
                             SequenceNumber   : 1, // Wij pikken altijd nummer 1 in
                             OrganizationId   : orgID,
                             AccountHolderName: bankdata.ACCOUNTHOLDERNAME.substr(0, 32),
                             AccountNumber    : bankdata.ACCOUNTNUMBER,
                             BankTypeId       : bankdata.BANKTYPEID,
                             Bic              : bankdata.BIC,
                             Iban             : bankdata.IBAN,
                             Preferred        : (bankdata.PREFERRED=="true")
                          };

            var url = "/api/" + database + "/" + apiU4Record + "/" + orgID + "/1.json"; // Altijd volgnummer 1
            var theData = unit4.apiUnit4("GET", url);
            if (theData)
            {   // Bestaande data is al opgehaald
                var method = "PUT";
            }
            else // new record
            {
                method = "POST";
                var url = "/api/" + database + "/" + apiU4Record;
                var theData = {};
            }
            for (var i in newData)
                theData[i] = newData[i];
            WScript.Echo("About to " + method + " " + url + "\n" + JSON.stringify(theData, null, '  '));

            var jresp = unit4.apiUnit4(method, url, theData);
        }
    }
}
