var OPCTechs_Giffer = (function () {
	"user strict";
	
	var _loadImage = function (src) {
		return new Promise((resolve, reject) => {
			var img = new Image();
			img.onload = () => resolve(img.height);
			img.onerror = reject;
			img.src = src;
			if (img.complete) {
				resolve(img.height);
			}
		});
	}
	
	var _isGifImage = function (el) {
		return /^(?!data:).*\.gif/i.test(el.src);
	}
	
	var _freezeGif = async function (el) {
		var canvas = document.createElement("canvas");
		var w = canvas.width = el.width * 1;
		var h = canvas.height = el.height * 1;
		var src = el.src;
		if (_isGifImage(el)) { 
			el.setAttribute("data-origin-src", src);
		}
		canvas.getContext("2d").drawImage(el, 0, 0, w, h);
		el.src = canvas.toDataURL("image/gif");
	}
	
	return {
		initial: async function (el, { value }) {
			el.setAttribute("data-origin-src", el.src);
			OPCTechs_Giffer.update(el, { value });
		},
		update: async function (el, { value }) {
			el.__proto__.$play = _ => { }
			el.__proto__.$stop = _ => { }
			if (typeof value != "boolean") {
				return;
			};
			var originSrc = el.getAttribute("data-origin-src");
			if (!_isGifImage(el) && !originSrc) {
				return;
			};
			await _loadImage(el.src);
			await new Promise(resolve => setTimeout(resolve, 0));
			el.__proto__.$play = OPCTechs_Giffer.play.bind(el);
			el.__proto__.$stop = OPCTechs_Giffer.stop.bind(el);
			if (!value) {
				_freezeGif(el);
			} else {
				el.$play();
			}
		},
		play: function () {
			var originSrc = this.getAttribute("data-origin-src");
			this.setAttribute("src", originSrc);
		},
		stop: function () {
			_freezeGif(this);
		}
	}
})();

Vue.directive("giffer", {
	bind: OPCTechs_Giffer.initial,
	updated: OPCTechs_Giffer.update,
	componentUpdated: OPCTechs_Giffer.update
});