var async = require('async')
, wd = require('wd')
, _ = require('underscore')
, utils = require('wd/lib/utils')
module.exports = {
ensureCookie: ensureCookie,
fillInForm: fillInForm,
asyncFunction: asyncFunction,
valueBy: valueBy,
clickBy: clickBy,
waitAndClick: waitAndClick,
waitAndGet: waitAndGet
};
function valueBy(driver, using, value, done) {
driver.element(using, value, function (err, el) {
if (err) return done(err)
driver.getValue(el, function (err, value) {
done(err, value, el)
})
})
}
function clickBy(driver, using, value, done) {
driver.element(using, value, function (err, el) {
if (err) return done(err)
el.click(function (err) {
return done(err, el)
})
})
}
function waitAndClick(driver, using, value, timeout, done) {
driver.waitAndGet(using, value, timeout, function (err, elements) {
if (err) return done(err)
if (!elements.length) return done(new Error('Element not found'))
elements[0].click(done)
})
}
function waitAndGet(driver, using, value, timeout, done) {
var endTime = Date.now() + timeout;
var poll = function(){
driver.elements(using, value, function(err, elements){
if(err){
return done(err);
}
if (elements.length) {
done(null, elements);
} else {
if(Date.now() > endTime){
done(new Error("Element didn't appear"));
} else {
setTimeout(poll, 200);
}
}
});
};
poll();
}
var extension = {};
for (var name in module.exports) {
extension[name] = wrap(module.exports[name]);
}
module.exports.extension = extension;
module.exports.parseFunction = parseFunction;
_.each(utils.elementFuncTypes, function(type) {
extension['value' + utils.elFuncSuffix(type)] = function(value, cb) {
valueBy.apply(this, [this, utils.elFuncFullType(type), value, cb]);
};
extension['click' + utils.elFuncSuffix(type)] = function(value, cb) {
clickBy.apply(this, [this, utils.elFuncFullType(type), value, cb]);
};
extension['waitAndGet' + utils.elFuncSuffix(type)] = function(value, timeout, cb) {
waitAndGet.apply(this, [this, utils.elFuncFullType(type), value, timeout, cb]);
};
extension['waitAndClick' + utils.elFuncSuffix(type)] = function(value, timeout, cb) {
waitAndClick.apply(this, [this, utils.elFuncFullType(type), value, timeout, cb]);
};
});
function wrap(fn) {
return function () {
return fn.apply(null, [this].concat([].slice.call(arguments)));
};
}
function parseFunction(method) {
var text = method.toString()
, body = text.substring(text.indexOf('{') + 1, text.lastIndexOf('}') - 1)
, args = text.split('(')[1].split(')')[0].split(',').map(Function.call.bind(''.trim))
, decl;
if (args.length !== method.length) {
throw new Error('Failed to parse async method: bad arguments. ' + JSON.stringify(args) + '; should be ' + method.length);
}
if (!args.length) return body;
decl = ' var ' + args.map(function (name, i) {
return name + ' = arguments[' + i + ']';
}).join('\n , ') + ';';
return decl + '\n' + body;
}