<?xml version="1.0"?>
<component>
<?component error="true" debug="true"?>
<registration
	description="scimOrgunits"
	progid="scimOrgunits.WSC"
	version="1.00"
	classid="{6D817B6F-9D08-4636-AAD9-8BD7C5EFF56A}"
>
</registration>

<public>

<!-- properties -->

<!-- methods -->
	<method name="initialize">
		<PARAMETER name="params"/>
	</method>
	<method name="error_handler">
		<PARAMETER name="code"/>
		<PARAMETER name="msg"/>
		<PARAMETER name="orgHandler"/>
	</method>
	<method name="transform_filter">
		<PARAMETER name="filter"/>
	</method>
	<method name="transform_outgoing">
		<PARAMETER name="params"/>
		<PARAMETER name="data"/>
	</method>
	<method name="transform_incoming">
		<PARAMETER name="params"/>
		<PARAMETER name="data"/>
	</method>
	<method name="get_eTag">
		<PARAMETER name="params"/>
		<PARAMETER name="data"/>
	</method>
</public>

<script language="javascript">
<![CDATA[

/*	properties	*/


/*	methods	*/
/*
/*
    $Id$

    File:   scimorgunits.wsc
*/
/* Globals */
var FCLT;

function initialize(params)
{
    FCLT = params;
}

function error_handler(code, msg, orgHandler)
{
    code = code || 500;
    var data = {
        "schemas" : ["urn:ietf:params:scim:api:messages:2.0:Error"],
        "scimType": "invalidValue",
        "detail"  : msg,
        "status"  : code
    };

    FCLT.DEZE.Response.ContentType = "application/json";
    FCLT.DEZE.Response.Write(FCLT.DEZE.JSON.stringify(data, null, 2));
    var codestr = String(code);
    if (typeof code == "number")
    {
        var codestr = { 400: "Bad request",
                        403: "Forbidden",
                        404: "Not Found",
                        422: "Unprocessable Entity" }[code];
        if (codestr)
            code = code + " " + codestr;
    }
    FCLT.DEZE.Response.Status = code;

    FCLT.DEZE.__Log("Aborting with status: " + code);
    FCLT.DEZE.__Log(data);

    FCLT.DEZE.Response.End;
}

function transform_filter(filter)
{
    if ("count" in filter)
        filter.limit = filter.count;
    if ("startindex" in filter) {
        filter.offset = filter.startindex - 1;
        filter.showall = 1;
    }
    if ("filter" in filter)
    {
        // Ontvangen filter: "filter": "id eq \"KFSG_department_703\""
        var v_filter = filter.filter.replace ("id eq \"" + FCLT.DEZE.customerId + "_department_", "");
        v_filter = v_filter.replace("\"", "");
        filter.id = v_filter;
    }
    return filter;
}

function get_eTag(params, data)
{
    if (data && typeof data == "object" && "meta" in data)
        return data.meta.version;
    return null;
}

function transform_incoming(params, data)
{
//FCLT.DEZE.__DoLog(data);
    var department =
    {
        externalid : data["externalId"],
        description: data["code"],
        name       : data["externalId"]
    };

    if (params.method == "POST") // niet zetten bij een PUT (die misschien alleen kostenplaatsen bijwerkt): dan kan onbedoeld een afdeling naar het default bedrijf gezet raken
    {
        if (FCLT.DEZE.S("scim_default_bedrijf") > 0)
        {
            department.company = FCLT.DEZE.S("scim_default_bedrijf");
        }
        else 
        {
            FCLT.DEZE._AiAi("Setting scim_default_bedrijf must have a value");
        }
    }

    if ("costCenter" in data && data["costCenter"] != "")
    {
        department.costcentre = { name: data["costCenter"] }; // id mag achterwege blijven omdat desc_is_unique
        var sql = "SELECT prs_kostenplaats_key FROM prs_kostenplaats "
                + "WHERE prs_kostenplaats_verwijder IS NULL "
                + "  AND prs_kostenplaats_nr = " + FCLT.DEZE.safe.quoted_sql(department.costcentre.name);
        var oRs = FCLT.DEZE.Oracle.Execute(sql);
        if (oRs.eof)
        {
            sql = "INSERT INTO prs_kostenplaats (prs_kostenplaats_nr, prs_kostenplaats_omschrijving, prs_kostenplaats_module) "
                + "VALUES (" + FCLT.DEZE.safe.quoted_sql(department.costcentre.name) + "," + FCLT.DEZE.safe.quoted_sql(department.costcentre.name) + ",'PRS')";
            FCLT.DEZE.Oracle.Execute(sql);
        }
        oRs.Close();
    }
    else
        department.costcentre = { name: "" };

    return { department: department };
}

function transform_one_department(params, department)
{
    FCLT.DEZE.__Log(department);


    var unique = FCLT.DEZE.customerId + "_department_" + String(department.id);

    var onedepartment = {
           "code":department.description,
           "externalid":department.externalid,
           "id":unique,
           "schemas":[
              "urn:ietf:params:scim:schemas:extension:2.0:OrgUnit",
              "urn:ietf:params:scim:schemas:extension:enterprise:2.0:OrgUnit"
           ],
           "meta":{
              "created":department.created,
              "lastModified":department.lastchange?department.lastchange:department.created,
              "location":FCLT.DEZE.HTTP.urlzelf() + "/appl/SCIM/OrgUnits/" + unique,
              "resourceType":"OrgUnit"
           }
        }

    if (department.costcentre)
    {
       onedepartment.costCenter = department.costcentre.name;
    }

    var oCrypto = new ActiveXObject("SLNKDWF.Crypto");
    var eTag = '"' + oCrypto.hex_sha1(FCLT.DEZE.JSON.stringify(onedepartment)).toLowerCase() + '"';
    onedepartment.meta["version"] = "W/" + eTag; // Weak eTag?
    return onedepartment;
}

function transform_outgoing(params, data)
{
    if ("department" in data)
    {
        var onedepartment = transform_one_department(params, data.department);
        return onedepartment;
    }
    if ("departments" in data)
    {
        var alldepartments = [];
        for (var i = 0; i < data.departments.length; i++)
        {
            var department = data.departments[i];
            alldepartments.push(transform_one_department(params, department));
        }

        return {
        	"totalResults": data.total_count,
        	"itemsPerPage": alldepartments.length,
        	"startIndex": 1,
        	"schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
        	"Resources": alldepartments
        };
    }
}

]]>
</script>
</component>
