var _ = require("underscore");
var Cookie = require("cookie");
var Util = require("util");

function decr(r) {
	var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@!~*-_.()'".split("");
	var n = [];
	var a = [];
	r.split("").reverse().forEach(function (r, t) {
		var o = e.indexOf(r);
		if (parseInt((t + 1) % 2) == 1) {
			a.push(o)
		} else {
			var p = parseInt(o - a[(t + 1) / 2 - 1]);
			n.push(e[p])
		}
	});
	var t = n.join("").replace(/@/g, "%");
	return decodeURIComponent(t)
};

function getJsApi(req, params) {
	var REQ_URL = 'http://video.duowan.com/jsapi/';

	var defer = $.Deferred();

	$.ajax({
		url: REQ_URL + req + "/",
		data: params,
		dataType: 'jsonp'
	}).done(function () {
		defer.resolveWith(this, arguments);
	}).fail(function () {
		defer.rejectWith(this, arguments);
	});

	setTimeout(function () {
		defer.notify("timeout");
	}, 10000);

	return defer;
}

function getBaseApi(req, params) {
	var REQ_URL = 'http://video.duowan.com/';

	var defer = $.Deferred();

	$.ajax({
		url: REQ_URL + "?r=" + req,
		data: params,
		dataType: 'jsonp'
	}).done(function () {
		defer.resolveWith(this, arguments);
	}).fail(function () {
		defer.rejectWith(this, arguments);
	});

	setTimeout(function () {
		defer.notify("timeout");
	}, 10000);

	return defer;
}

class Request {
	constructor() {
		this.opts = {
			domain: true,
			url: true
		}
	}

	/**
	 * 获取视频详情
	 * @param {*视频id} vids 
	 */
	getVideoInfo(vids) {
		return getJsApi("playPageVideoInfo", {
			vids : vids
		});
	}

	/**
	 * 获取博客选集
	 * @param {*用户id} uid 
	 */
	getUserVideos(uid) {
		return getJsApi("getUserVideos", {
			uid : uid
		});
	}

	/**
	 * 获取某视频的相关视频
	 * @param {*视频id} vid 
	 */
	getVideoRelate(vid) {
		return getJsApi("getVideoRelate", {
			relate_vid : vid
		})
	}

	/**
	 * 获取单个视频的被收藏数
	 * @param {*视频id} vid 
	 */
	getCollectNumByVid(vid) {
		return getJsApi("GetCollectNumByVid", {
			vids : vid
		})
	}

	isVideoCollected(vids) {
		return getJsApi("isVideoCollected", {
			vids : vids
		})
	}

	/**
	 * 收藏视频
	 * @param {*视频id} vid 
	 */
	doCollectByVid(vid) {
		return getJsApi("collectByVid", {
			vids : vid
		})
	}

	/**
	 * 点赞
	 * @param {*视频id} vid 
	 */
	doSupport(vid) {
		return getBaseApi("video/support", {
			vid : vid
		})
	}

	doSubscribe(uid) {
		return getBaseApi("subscribe/subscribe", {
			uid : uid
		})
	}

	getUserSubscribe() {
		return getJsApi("getUserSubscribe", {
		})
	}

	/**
	 * 获取视频分P播放列表
	 * @param {*视频id} vid 
	 * @param {*文章id} articleId 
	 * @param {*所属频道} channel 
	 */
	getVideoParts (vid, articleId, channel) {
		return ("getVideoParts", {
			vid : vid,
			articleId : articleId,
			channel : channel
		})
	}

	/**
	 * 解密数据
	 */
	deCodeArg(target) {
		var srcMap = {};
		if (JSON.parse) {
			srcMap = JSON.parse(decr(target)); 
		} else {
			srcMap = eval('('+decr(target)+')');
		}
		return srcMap;
	}
}

module.exports = Request;