/*STRAVA_API

{
  "file": /path/to/file.txt, // {File} The uploaded file.
  "name": name_example, // {String} The desired name of the resulting activity.
  "description": description_example, // {String} The desired description of the resulting activity.
  "trainer": trainer_example, // {String} Whether the resulting activity should be marked as having been performed on a trainer.
  "commute": commute_example, // {String} Whether the resulting activity should be tagged as a commute.
  "dataType": dataType_example, // {String} The format of the uploaded file.
  "externalId": externalId_example // {String} The desired external identifier of the resulting activity.
}


https://resmedglobal.atlassian.net/secure/CreateIssue.jspa?issuetype=2&pid=ISMS2
https://resmedglobal.atlassian.net/secure/CreateIssue.jspa?issuetype=3&pid=ISMS2

OAuth2.0 strava / pebble

1 - get activity:write authorization (once and for all)
    GET https://www.strava.com/oauth/authorize?client_id=94880&response_type=code&redirect_uri=http://strava.jonget.fr&approval_prompt=force&state=bike_companion&scope=activity:write
    monitor state, code and scope (as upload can be unchecked)!
    code is short lived and one time usage
2 - get tokens in exchange of code
    POST https://www.strava.com/oauth/token?client_id=94880&client_secret=08dc170f0fe38f39dd327bea82a28db4400e6f00&code=e0aeb60ea9f508d25974bb56ccb551be56b91470&grant_type=authorization_code
    refresh & access tokens + expiry of access token (6hours) retrieved

3 - test if access token expired

4a- if not, API call
    GET https://www.strava.com/api/v3/athlete with "Authorization" header ="Bearer XXXXX"  XXXXX=access token

4b- if yes refresh access token with refresh token get in 2
    POST https://www.strava.com/oauth/token?client_id=94880&client_secret=8a68d5b79f2fb3e00ad3eaa5025253990fbd6a58&refresh_token=c313d612768db4b12af2782372aa1d9349c265cb&grant_type=refresh_token
*/

gpxfile = b.getGpx(!0) // returned gpxfile is string
upload(gpxfile)

function getGpx(t) {
    if (0 == points.length) return "";
    if (creator = "Ventoo SE", gpxfile = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" creator="' + creator + '" version="1.1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd  http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd" xmlns:pb10="http://www.pebblebike.com/GPX/1/0/">\n', itemId = -1, trackNumber = 1, points.length > 0) {
        for (gpxfile += "<trk>\n<name>Track #1</name>\n<trkseg>\n", prevTime = -1, i = 0; i < points.length; i++) prevTime > 0 && points[i].t - prevTime > 43200 ? (trackNumber++, gpxfile += "</trkseg>\n</trk>\n<trk>\n<name>Track #" + trackNumber + "</name>\n<trkseg>\n") : prevTime > 0 && points[i].t - prevTime > 7200 && (gpxfile += "</trkseg>\n<trkseg>\n"), d = new Date(1e3 * points[i].t), ti = d.toISOString(), gpxfile += '<trkpt lat="' + points[i].la + '" lon="' + points[i].lo + '">\n  <ele>' + points[i].a + "</ele><time>" + ti + "</time>\n", !t && points[i].h || (gpxfile += "  <extensions>", t && (gpxfile += "<pb10:accuracy>" + points[i].ac + "</pb10:accuracy>"), points[i].h && (gpxfile += "<gpxtpx:TrackPointExtension>", gpxfile += "<gpxtpx:hr>" + points[i].h + "</gpxtpx:hr>", gpxfile += "</gpxtpx:TrackPointExtension>\n"), gpxfile += "</extensions>\n"), gpxfile += "</trkpt>\n", prevTime = points[i].t;
        gpxfile += "</trkseg>\n</trk>\n"
    }
    return gpxfile += "</gpx>\n", gpxfile
}

function upload(gpxfile) {
    params = {
            url: s,
            method: "POST",
            data: { description: "desc", data_type: "gpx" },
            files: { file: gpxfile },
        authorization: "Bearer " + c,
            callback: function() {
                var z = "";
                if (r && console.log(e.status + " - " + e.txt), 201 == e.status) z = "Your activity has been created";
                else if (400 == e.status) z = "An error has occurred. If you've already uploaded the current activity, please delete it in Strava.";
                else if (401 == e.status) z = "Error - Unauthorized. Please check your credentials in the settings.", o.setAccessToken("");
                else try { response_json = JSON.parse(e.txt), response_json.error ? (r && console.log("error:" + response_json.error), z = response_json.error, o.setAccessToken("")) : response_json.status && (r && console.log("status:" + response_json.status), z = response_json.status) } catch (z) { console.log("Error log, " + z) }
                z && Pebble.showSimpleNotificationOnPebble("Ventoo SE - Strava", z)
            }
        }
        //e[0] = params
    var XHR = new XMLHttpRequest
    console.log(e[0].url)
    XHR.open(e[0].method, e[0].url, !0)
    var r = Math.random().toString().substr(2);
    XHR.setRequestHeader("content-type", "multipart/form-data; charset=utf-8; boundary=" + r)
    e[0].authorization && XHR.setRequestHeader("Authorization", e[0].authorization);
    for (var i in e[0].data) o += "--" + r + '\r\nContent-Disposition: form-data; name="' + i + '"\r\n\r\n' + e[0].data[i] + "\r\n";
    for (var i in e[0].files) o += "--" + r + '\r\nContent-Disposition: form-data; name="' + i + '" ; filename=test.gpx\r\n\r\n' + e[0].files[i] + "\r\n";
    o += "--" + r + "--\r\n"

    XHR.onreadystatechange = function() {
        try {
            4 == XHR.readyState && (n.status = XHR.status, n.txt = XHR.responseText, n.xml = XHR.responseXML, e[0].callback && e[0].callback())
        } catch (t) {
            console.error("Error2 loading, ", t)
        }
    }
    XHR.send(o)
}