<% /*
    $Revision$
    $Id$

    File:           api2_swagger.inc
    Description:    Genereer OpenAPI compatible documentatie
                    zodat swagger ui die kan lezen
    Notes:
    Status:

*/
%>
<%
    function swaggerschema(model)
    {
        var schema = {
         "type":"object",
         "properties":{},
         "required": [],
         "xml":{
            "name": model.record_name
         }
        }
        for (var fld in model.fields)
        {
            if (fld.substring(0,1) == "_")
                continue;
            var field = model.fields[fld];
            if (field.hidden)
                continue;
            if (field.required)
                schema.required.push(fld);
            switch (field.typ)
            {
                case "key":
                    var prop = {
                       "type":"integer",
                       "format":"int64"
                    };
                    if (field.foreign)
                    {
                        prop = {
                            "type": "object",
                            "properties": {
                                "id": { "type": "integer", "format": "int64" },
                                "name": { "type": "string" }
                            }
                        }
                    }
                    if (fld == "id")
                        prop["readOnly"] = true; // Wordt nog genegeerd door Swagger-ui 2.0
                    break;
                case "float":
                case "currency":
                    var prop = {
                       "type":"number",
                       "format":"float"
                    };
                    break;
                case "number":
                    var prop = {
                       "type":"integer",
                       "format":"int64"
                    };
                    break;
                case "check":
                case "check0":
                    var prop = {
                       "type":"integer",
                       "format":"int64",
                       "enum":[0, 1]
                    };
                    break;
                case "varchar":
                case "memo":
                    var prop = {
                       "type":"string",
                       "format":"string"
                    };
                    break;
                case "date":
                    var prop = {
                       "type":"string",
                       "format":"date"
                    };
                    break;
                case "datetime":
                    var prop = {
                       "type":"string",
                       "format":"date-time"
                    };
                    break;
                default:
                    continue;
            }
            prop.description = field.label;
            //prop["default"] = field.defaultvalue;
            if ("LOV" in field)
            {
                var spl = api2.splitLOV(field.LOV);
                var enums = [];
                for (var l in spl)
                {
                    enums.push(l);
                }
                prop["enum"] = enums;
            }
            schema["properties"][fld] = prop;
        }
        return schema;
    };

    function swaggermodel (model)
    {
        //if ("autfunction" in model && !user.has(model.autfunction))
        //    return {};
        var auttext = "";
        if ("autfunction" in model)
        {
            if (typeof model.autfunction == "string")
                auttext = "Requires authorization `{0}` ({1})".format(model.autfunction, L("lcl_" + model.autfunction));
            else if (typeof model.autfunction == "object" && model.autfunction instanceof Array && model.autfunction.length)
            {
                var lcls = [];
                for (i in model.autfunction)
                    lcls.push(L("lcl_" + model.autfunction[i]));
                auttext = "Requires authorization `{0}` ({1})".format(model.autfunction.join(" or "), lcls.join(", "));
            }
        }
        model.records_title = model.records_title || model.records_name;
        model.record_title  = model.record_title || model.record_name;
        var result = {
            "schema": { "fields": {} },
            "get": {
              "tags":[
                 getQParamSafe("swmodule", "XXX")
              ],
              "summary": "Get all `{0}`".format(model.records_title),
              "description": "Returns all `{0}` from the system that the user has access to.".format(model.records_title) + "<br>" + auttext,
              "responses": {
                "200": {
                  "description": "A list of `{0}`".format(model.records_title),
                  "schema":  {
                        "$ref": "#/schema/fields/" + model.record_name + "fields"
                    }
                },
                "403": {
                  "description": "Forbidden"
                }
              },
            "security":[
               {
                  "api_key":[
                  ]
               }
            ],
            "parameters": []
            }
        };

        if (model.includes)
        {
            var enums = [];
            for (var i in model.includes)
                enums.push(i);
            var inc = model.includes[i];
            result["get"].parameters.push(
                {
                  "name": "include",
                  "in": "query",
                  "description": "Include all `{0}`".format("model" in inc?(inc.model.records_title||inc.model.records_name):i),
                  //"required": false,
                  "type": "array",
                  "enum": enums
                });
        };

        result["schema"]["fields"][model.record_name + "fields"] = swaggerschema(model);
        result["schema"][model.records_name] =
                       {
                       "type": "object",
                       "properties": {
                            "total_count": {
                                   "type":"integer",
                                   "format":"int64",
                                   "example": 10,
                                   "xml": {
                                     "attribute": true
                                   }
                            },
                            "limit": {
                                   "type":"integer",
                                   "format":"int64",
                                   "example": S("qp_maxrows"),
                                   "xml": {
                                     "attribute": true
                                   }
                            },
                            "offset": {
                                   "type":"integer",
                                   "format":"int64",
                                   "example": 0,  // Doen we altijd nog
                                   "xml": {
                                     "attribute": true
                                   }
                            }
                       }
                    }
        result["schema"][model.records_name]["properties"][model.records_name] =
                      {
                        "type": "array",
                        "items": {
                            "$ref": "#/schema/fields/" + model.record_name + "fields"
                        }
                      };

        result["schema"][model.record_name] = {
                        "type": "object",
                        "properties": {}
                    };
        result["schema"][model.record_name ]["properties"][model.record_name] =
                        {
                            "$ref": "#/schema/fields/" + model.record_name + "fields"
                        }

        if (getQParamInt("single", 0) == 1)
        {

            result["get"].tags = [ getQParamSafe("swmodule", "XXX") ];
            result["get"].summary = "Get one `{0}`".format(model.record_title);
            result["get"].description = "Returns the `{0}`.".format(model.record_title) + "<br>" + auttext,

            result["get"].parameters.push(
               {
                  "name":"id",
                  "in":"path",
                  "description":"ID of `{0}` to return".format(model.record_title),
                  "required":true,
                  "type":"integer",
                  "format":"int64"
               }
            );
            result["get"]["responses"]["200"] =
              {
                "description": "A `{0}` to be returned".format(model.record_title),
                "schema": {
                    "$ref": "#/schema/fields/" + model.record_name + "fields"
                }
              };
        }
        if (getQParamInt("single", 0) == 0 && model["REST_POST"])
        {
            result["post"] = {
                    "tags":[
                       getQParamSafe("swmodule", "XXX")
                    ],
                    "summary":"Add a new `{0}`".format(model.record_title),
                    "description": auttext,
                    "operationId":"add" + model.records_name,
                    "parameters":[
                       {
                          "in":"body",
                          "name":"body",
                          "description":"`{0}` object that needs to be added".format(model.record_title),
                          "required":true,
                          "schema": {
                            "$ref": "#/schema/fields/" + model.record_name + "fields"
                          }
                       }
                    ],
                    "responses":{
                        "200": {
                            "description": "A `{0}`".format(model.record_title),
                            "schema": {
                                "$ref": "#/schema/fields/" + model.record_name + "fields"
                            }
                        },
                       "400":{
                          "description":"Bad request"
                       },
                       "403": {
                          "description": "Forbidden"
                       }
                    },
                    "security":[
                       {
                          "api_key":[]
                       }
                    ]
                 }
        }
        if (getQParamInt("single", 0) == 1 && model["REST_PUT"])
        {
            result["put"] = {
                    "tags":[
                       getQParamSafe("swmodule", "XXX")
                    ],
                    "summary":"Update one `{0}`".format(model.record_title),
                    "description": "Update an existing `{0}`".format(model.record_title) + "<br>" + auttext,
                    "operationId":"add" + model.records_name,
                    "parameters":[
                       {
                          "name":"id",
                          "in":"path",
                          "description":"ID of `{0}` to update".format(model.record_title),
                          "required":true,
                          "type":"integer",
                          "format":"int64"
                       },
                       {
                          "in":"body",
                          "name":"body",
                          "description":"`{0}` object that needs to be updated".format(model.record_title),
                          "required":true,
                          "schema": {
                            "$ref": "#/schema/fields/" + model.record_name + "fields"
                          }
                        }
                    ],
                    "responses":{
                        "200": {
                            "description": "A `{0}`".format(model.record_title),
                            "schema": {
                                "$ref": "#/schema/fields/" + model.record_name + "fields"
                            }
                        },
                       "403": {
                          "description": "Forbidden"
                       },
                       "400":{
                          "description":"Bad request"
                       }
                    },
                    "security":[
                       {
                          "api_key":[ ]
                       }
                    ]
                 }
        }
        if (getQParamInt("single", 0) == 1 && model["REST_DELETE"])
        {
            result["delete"] = {
                    "tags":[
                       getQParamSafe("swmodule", "XXX")
                    ],
                    "summary":"Delete one `{0}`".format(model.record_title),
                    "description": auttext,
                    "operationId":"add" + model.records_name,
                    "parameters":[
                       {
                          "name":"id",
                          "in":"path",
                          "description":"ID of `{0}` to delete".format(model.record_title),
                          "required":true,
                          "type":"integer",
                          "format":"int64"
                       }
                    ],
                    "responses":{
                       "204":{
                          "description":"No content (delete succesfull or record not found)"
                       },
                       "403": {
                          "description": "Forbidden"
                       }
                    },
                    "security":[
                       {
                          "api_key":[ ]
                       }
                    ]
                 }
        }
        return result;
    }

%>