<% /*
    $Revision$
    $Id$

    File:           scaffolding_save.asp
    Description:    save information from scaffolding_edit.asp

    Parameters:

    Context:
    Note:

*/

function scaffolding_save(model, scf_params)
{
    protectRequest.validateToken();
    var key = getQParamInt( "id" );
    var multi = getFParamInt( "scf_multi", 0 ) == 1;
    var cloning = getQParamInt( "scf_clone", 0 ) == 1;
    if (cloning)
    {
        var clone_key = key;
        key = -1;
    }

    var formfields = [];
    for (var fld in model.fields)
    {
        var field = model.fields[fld];
        if (fld == "id")
            continue;
        if (fld.readonly)
            continue;
        if (field.insertonly && key > 0)
            continue;
        formfields.push({ name: fld, frm: fld });
    }

    var params = { filter: { "id": key } };
    if (!(key > 0))
        params.multiadd = scf_params.incsetting && scf_params.incsetting.multiadd;

    var jsondata = api2.form2JSONdata(model, params, formfields);

    if (cloning)
    {
        // Bepaal de mee te nemen includes van de oude data
        var incs = [];
        for (var inc in model.includes)
        {
            var include = model.includes[inc];
            if (include.enable_update && !model.includes[inc].notransport)
                incs.push(inc)
        }
        var olddata = api2.GET(model, clone_key, { include: incs, internal: true } );
        for (var fld in model.fields)
        {
            var field = model.fields[fld];
            if (field.insertonly)
                jsondata[fld] = olddata[fld];
            else if (field.required && !(fld in jsondata)) // Bijvoorbeeld kenmerktypeLOV's die je niet mag togglen
                jsondata[fld] = olddata[fld];
        }
        for (var inc in model.includes)
        {
            var include = model.includes[inc];
            if (include.enable_update && !model.includes[inc].notransport)
                jsondata[inc] = olddata[inc];
        }
        __Log("Cloning data:");
        __Log(jsondata);
    }

    params.properties = { extraserie: false,
                          nameprefix: "k"
                        };
    if (model.includes && "custom_fields" in model.includes)
        jsondata.custom_fields = flexkenmerken2jsondata(params.properties);

    if (multi)
    {
        var anyleft = false;
        for (var fld in jsondata) // Alle velden waar ons vinkje niet voor stond slaan we niet op
        {
            var cb_name = "scf_multi_" + fld;
            if (getFParam(cb_name, "off") != "on")
                delete jsondata[fld];
            else
                anyleft = true;
        }
        var key = getFParamIntArray("scf_multi_id"); // voor resultaat
        if (anyleft)
        {
            var keys = getFParamIntArray("scf_multi_id");
            for (var i = 0; i < keys.length; i++)
            {
                if ( ("hook_pre_put" in model) || ("hook_post_put" in model))
                {
                    // -- huidige data voor de key ophalen
                    //    dat gebruikt kan worden in de hook_pre_put en/of hook_post_put
                    var xxx_params = { "filter": { "id": keys[i], "show_deleted": "off"}, "id_only": true};  // data moet hetzelfde zijn als bij het wijzigen van 1 record.
                    var xxx_data = model.REST_GET(xxx_params)[0];
                    // -- data aanpassen met multi waarden
                    for (var n = 0; n < formfields.length; n++)
                    {
                        for (var fld_n in jsondata)
                        {
                            if (formfields[n].name == fld_n)
                                xxx_data[fld_n] = jsondata[fld_n];
                        }
                    }

                    if ("hook_pre_put" in model)
                        model.hook_pre_put(params, xxx_data, keys[i], jsondata); // Behalve alle data van het record wordt ook de gewijzigde multi-select-velden meegestuurd.
                    var restresult = model.REST_PUT(params, xxx_data, keys[i]);
                    if ("hook_post_put" in model)
                        model.hook_post_put(params, xxx_data, keys[i], jsondata);
                }
                else
                {
                    var restresult = model.REST_PUT(params, jsondata, keys[i]);
                }
            }
        }
        else
            var restresult = { toaster: L("lcl_scf_no_changes") };
    }
    else if (key > 0)
    {
        if ("hook_pre_put" in model)
            model.hook_pre_put(params, jsondata, key);
        var restresult = model.REST_PUT(params, jsondata, key);
        if ("hook_post_put" in model)
            model.hook_post_put(params, jsondata, key);
    }
    else
    {
        if ("hook_pre_post" in model)
            model.hook_pre_post(params, jsondata);
        if (params.multiadd)
        {
            key = [];
            var arr = jsondata[params.multiadd]; // Dit zal dan een Array zijn
            if (arr)
                for (var i = 0; i < arr.length; i++)
                {
                    if (arr[i] > 0)
                    {
                        jsondata[params.multiadd] = arr[i];
                        var restresult = model.REST_POST(params, jsondata);
                        key.push.apply(key, [restresult.key]); // Ook array aan array kunnen toevoegen.
                    }
                }
            else
                restresult = {};
        }
        else
        {
            params.cloning = cloning;
            var restresult = model.REST_POST(params, jsondata);
            key = restresult.key;

            if ("hook_post_post" in model)
                model.hook_post_post(params, jsondata, key);

            if (cloning)
            {
                // Vertalingen ook nog
                // Vooralsnog alleen van het hoofd-record ('eigen tabel omschrijving')
                // Ook van alle children ('eigen tabel waarde omschrijving') is veel ingewikkelder
                var transcols = [];
                for (var fld in model.fields)
                {
                    var field = model.fields[fld];
                    if (field.translate)
                        transcols.push(field.dbs);
                }
                if (transcols.length)
                {
                    var sql = "INSERT INTO fac_locale"
                            + "       (fac_locale_tekst,"
                            + "        fac_locale_lang,"
                            + "        fac_locale_kolomnaam,"
                            + "        fac_localeitems_key,"
                            + "        fac_locale_dialect_key,"
                            + "        fac_locale_kolomkeyval)"
                            + " SELECT fac_locale_tekst,"
                            + "        fac_locale_lang,"
                            + "        fac_locale_kolomnaam,"
                            + "        fac_localeitems_key,"
                            + "        fac_locale_dialect_key, "
                            +          key
                            + "   FROM fac_locale"
                            + "  WHERE fac_locale_kolomkeyval = " + clone_key
                            + "    AND fac_locale_kolomnaam IN ({0})".format(safe.quoted_sql_join(transcols, true));
                    Oracle.Execute(sql);
                }
            }
        }
    }

    // Met params.toaster kan een melding worden meegegeven vanuit de hook functies.
    // Deze wordt alleen getoond als scaffolding_save geen toaster zet.
    var result = { key: key,
                   warning: restresult.warning,
                   toaster: (restresult.toaster ? restresult.toaster : (params.toaster ? params.toaster : "")),
                   keepForm: !!restresult.warning,
                   reload: ("reload_after_save" in model ? model.reload_after_save : false),
                   success: true };
    Response.ContentType = "application/json";
    Response.Write(JSON.stringify(result));
}
%>
