'use strict';

var messaging = require('./messaging.js');

function functionFromString(funcOrString) {
    if (typeof funcOrString === 'function') {
        return funcOrString;
    }
    return eval('(' + funcOrString.toString() + ')');
}

function persistToDOM(object, funcString, data) {
    data = data || {};
    data.type = "lively4script";
    $("<script>").attr(data).text(funcString).appendTo(object);

    var world = $("html").clone();
    world.find("#editor").empty();
    world.find("#console").empty();
    var s = new XMLSerializer();
    var content = "<!DOCTYPE html>" + s.serializeToString(world[0]);

    var url = document.URL;
    var r = /https:\/\/([\w-]+)\.github\.io\/([\w-]+)\/(.+)/i;
    var results = url.match(r);

    writeFile(results[2], results[3], results[1], content);
}

function writeFile(repo, path, user, content) {
    return messaging.postMessage({
        meta: {
            type: 'github api'
        },
        message: {
            credentials: {
                token: localStorage.GithubToken,
                auth: 'oauth'
            },
            topLevelAPI: 'getRepo',
            topLevelArguments: [user, repo],
            method: 'write',
            args: ['gh-pages', path, content, 'auto commit']
        }
    }).then(function(event) {
        return event;
    });
}

export function addScript(object, funcOrString, opts) {
    if (object instanceof jQuery) {
        jQuery.each(object, function(k, v) {
            addScript(v, funcOrString, opts);
        });
        return;
    }

    opts = opts || {};
    if (typeof object.__scripts__ === 'undefined') {
        object.__scripts__ = {};
    }

    var func = functionFromString(funcOrString);
    if (typeof func !== 'function') {
        throw 'no valid function provided!';
    }

    var name = func.name || opts.name;
    if (!name) {
        throw 'cannot add script without name!';
    }

    if (typeof object[name] !== 'undefined') {
        throw 'script name "' + name + '" is already reserved!';
    }

    object.__scripts__[name] = object[name] = func.bind(object);

    persistToDOM(object, func.toString(), {"data-name": name});
}

export function callScript(object, name) {
    var optionalArgs = [].splice.call(arguments, 2);
    if (object instanceof jQuery) {
        jQuery.each(object, function(k, v) {
            var args = [v, name];
            args = args.concat(optionalArgs);
            callScript.apply(this, args);
        });
        return;
    }
    if (typeof object.__scripts__ !== 'undefined' && typeof object.__scripts__[name] !== 'undefined') {
        return object[name].apply(object, optionalArgs);
    }
    throw 'unknown script "' + name +'"!'
}

@@ -230,24 +230,209 @@
  + ')');%0A%7D%0A%0A
+function getURL()%7B%0A    var baseurl = $('#baseurl').val() // How to abstract from UI? #TODO #JensLincke%0A    var filename = $('#filename').val()%0A    return new URL(baseurl + filename)%0A%7D%0A%0A
 function per
@@ -807,704 +807,478 @@
     
-var url = document.URL;%0A    var r = /https:%5C/%5C/(%5B%5Cw-%5D+)%5C.github%5C.io%5C/(%5B%5Cw-%5D+)%5C/(.+)/i;%0A    var results = url.match(r);%0A%0A    writeFile(results%5B2%5D, results%5B3%5D, results%5B1%5D, content);%0A%7D%0A%0Afunction writeFile(repo, path, user, content) %7B%0A    return messaging.postMessage(%7B%0A        meta: %7B%0A            type: 'github api'%0A        %7D,%0A        message: %7B%0A            credentials: %7B%0A                token: localStorage.GithubToken,%0A                auth: 'oauth'%0A            %7D,%0A            topLevelAPI: 'getRepo',%0A            topLevelArguments: %5Buser, repo%5D,%0A            method: 'write',%0A            args: %5B'gh-pages', path, content, 'auto commit'%5D%0A        %7D%0A    %7D).then(function(event) %7B%0A        return event;
+writeFile(content);%0A%7D%0A%0Afunction writeFile(content) %7B%0A    var url = getURL()%0A    console.log(%22%5Bscript-manager%5D save %22 + url)%0A    $.ajax(%7B%0A        url: url,%0A        type: 'PUT',%0A        data: currentEditor().getValue(),%0A        success: function(text) %7B%0A            console.log(%22%5Bscript-manager%5D file %22 + url + %22 written.%22)%0A        %7D,%0A        error: function(xhr, status, error) %7B%0A            console.log(%22%5Bscript-manager%5D could not write %22 + url + %22: %22 + error)%0A        %7D
 %0A   

use REST api to save file after adding scripts