#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

# @file rest example program for the RestClient module

/*  Copyright 2013 - 2015 David Nichols

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

%new-style
%enable-all-warnings
%require-types
%strict-args

%requires RestClient

#! program options
const opts = (
    "proxy": "proxy-url,p=s",
    "to": "timeout,t=i",
    "verbose": "verbose,v:i+",
    "help": "h,help",
    );

#! recognized HTTP methods
const Methods = (
    "GET": True,
    "PUT": True,
    "POST": True,
    "DELETE": True,
    );

main();

sub usage() {
    printf("usage: %s [options] get|put|post|delete URL ['qore msg body']
 -p,--proxy-url=ARG  set the proxy URL (ex: http://proxy:port)
 -t,--timeout=ARG    set HTTP timeout in seconds
 -v,--verbose        show more info (-v = response headers, -vv = msgs,
                     -vvv = all info)
 -h,--help           this help text
", get_script_name());
    exit(1);
}

any sub parse_arg(string arg) {
    # try to evaluate as a Qore expression
    string str = sprintf("any sub get() { return %s; }", arg);
    Program prog();
    try {
        prog.parse(str, "main");
        return prog.callFunction("get");
    }
    catch (hash ex) {
        return arg;
    }
}

sub main() {
    GetOpt g(opts);
    hash opt = g.parse3(\ARGV);

    if (opt.help || !ARGV[0])
        usage();

    *string meth = shift ARGV;
    if (!meth)
        usage();
    meth = meth.upr();
    if (!Methods{meth}) {
        printf("ERROR: unrecognized HTTP method %y; allowed methods: %y\n", meth, Methods.keys());
        usage();
    }

    *string url = shift ARGV;
    if (!url) {
        printf("ERROR: missing URL for REST server\n");
        usage();
    }

    hash opts.url = url;

    if (opt.proxy)
        opts.proxy = opt.proxy;

    if (opt.to) {
        int to = opt.to * 1000;
        opts += (
            "timeout": to,
            "connect_timeout": to,
            );
        }

    RestClient rest(opts);

    hash info;
    any body = shift ARGV;
    if (exists body)
        body = parse_arg(body);
    #printf("body: %y\n", body);
    try {
        any ans = rest.doRequest(meth, "", body, \info);
        switch (opt.verbose) {
            case NOTHING:
            case 0: printf("%N\n", ans.body); break;
            case 1: printf("response headers: %N\nresponse body:\n%N\n", info."response-headers" - "body", ans.body); break;
          default: {
              printf("request URI: %s\n", info."request-uri");
              printf("request headers: %N\n", info.headers);
              if (info."request-body")
                  printf("request body: %s\n", info."request-body");
              printf("response URI: %s\n", info."response-uri");
              printf("response headers: %N\n", info."response-headers" - "body");
              if (info."response-body")
                  printf("response body: %s\n", info."response-body");
              break;
            }
        }
    }
    catch (hash ex) {
        printf("%s: %s: %s", get_ex_pos(ex), ex.err, ex.desc);
        if (ex.arg) {
            print(": ");
            if (ex.arg.body.typeCode() == NT_STRING)
                print(ex.arg.body);
            else
                printf(ex.arg.typeCode() == NT_STRING ? "%s" : "%y", ex.arg);
        }
        print("\n");
    }
}
