Registry.require(["promise","helper","xmlhttprequest","cloud","tools"],function(){var l=Registry.log,b=Registry.get("promise"),A=Registry.get("helper"),G=Registry.get("xmlhttprequest").run,w=Registry.get("cloud"),z=Registry.get("tools"),m=0,t={ePASTEBIN:1,eCHROMESYNC:2,eSYNCFS:3,eGDRIVE:4,eDROPBOX:5},x=[],r=!1,v=null,y=[{method:"HEAD",url:"https://www.google.com",extract:function(a,b){try{for(var c=b?b.split("\n"):[],e=0;e<c.length;e++){var n=c[e].split(":"),l=n.shift()||"",f=n.join(":")||"";if("date"==
l.trim().toLowerCase()&&f)return new Date(f)}}catch(m){}return null}},{method:"GET",url:"https://json-time.appspot.com/time.json",extract:function(b){try{var d=JSON.parse(b);if(!d.error&&d.datetime)return new Date(d.datetime)}catch(c){}return null}}],k=function(){var a=function(a,c){var f=w[a]("sync"),d=function(b,q){if(q==m){var h=b.name,a=/.user.js$/;l.debug("si: cloud file changed",h,b);(h.match(/.meta.json$/)||h.match(a))&&x.forEach(function(b){b(h)})}},e={},k;return{init:function(){return b.Pledge().then(function(){if(!f.credentials)return f.list()}).then(function(){k||
(k=f.changes.listen(),k.progress(function(b){d(b,c)}));return!0})},list:function(b){return f.list(b).then(function(b){e={};var h={},a={},c,u,B=Date.now();b.forEach(function(g){e[g.name]=g;var p=/.meta.json$/,b=/.user.js$/;if(g.modified>B)l.debug("si: ignore future list item",B,g);else if((c=g.name.match(p))||(u=g.name.match(b)))c?(g.uuid=p=g.name.replace(p,""),g.lastModified=g.modified,g.precision=g.precision,h[p]=g):u&&(p=g.name.replace(b,""),a[p]=g)});return Object.keys(h).map(function(g){var p;
if(p=h[g])return p.source=a[g],p.options=p.options||{},p}).filter(function(g){return g})})},setSource:function(a,q){var h=a+".user.js",c=e[h],d;return b.Pledge(!1).then(function(){if(c&&f.compare)return f.compare(c,q)}).then(function(u){if(u)return l.debug("si: remote source data matches, skip upload of",h),b.Pledge();d=new Blob([q],{type:"text/plain"});return f.put(c||h,d)})},getSource:function(a,c){var h=a+".user.js",d=e[h];if(d)return b.Pledge(!1).then(function(){if(c&&f.compare)return f.compare(d,
c)}).then(function(a){return a?(l.debug("si: remote source data matches, skip download of",h),b.Pledge(c)):f.get(d).then(z.readAsText)});l.warn("si: list cache does not contain this UUID",a);return b.Breach()},getMeta:function(a){var c;return(c=e[a+".meta.json"])?f.get(c).then(z.readAsText).then(function(b){var d;var e=null;try{e=JSON.parse(b)}catch(u){}e&&e.uuid?b=e:(l.debug("si: unable to parse extended info of undefined"),b=null);if((d=b)&&(d.uuid=a))return d.lastModified=c.modified||d.lastModified,
d.precision=c.precision,d.options=d.options||{},d}):b.Breach()},setMeta:function(b,a){var c=new Blob([JSON.stringify(b)],{type:"text/plain"}),d=b.uuid+".meta.json";return f.put(e[d]||d,c,a)},remove:function(b){b.options.removed=Date.now()+v;var a=new Blob([JSON.stringify(b)],{type:"text/plain"});return f.put(b.uuid+".meta.json",a).then(function(){var a;if(a=e[b.uuid+".user.js"])return f.delete(a)})},reset:function(){return f.list(!0).then(function(b){return b=b.filter(function(b){var a=/.user.js$/;
return b.name.match(/.meta.json$/)||b.name.match(a)})}).then(function(a){var c=[];a.forEach(function(a){c.push(function(){var c=b();f.delete(a).always(function(){c.resolve()});return c.promise()}())});return b.when(c).always(function(){e={}})})}}},d=a("drive",t.eGDRIVE),a=a("dropbox",t.eDROPBOX),c=function(){var a=!1,c,d=function(a,d){m==t.eCHROMESYNC&&"sync"==d&&b.Pledge().then(function(){if(null===v)return C()}).then(function(){var b=new RegExp(c+"$");a&&Object.keys(a).forEach(function(c){var e=
a[c];l.debug('si: storage key "%s" in namespace "%s" changed. Old value was "%s", new value is "%s".',c,d,e.oldValue,e.newValue);if(-1!=c.search(b))for(var f=0;f<x.length;f++)if(!h[c]){var n=r(e.newValue,c);if(n)x[f](c,n)}})})},e=function(a){var c=b(),g=[];a?k().done(function(b){g=A.select(b,function(b){return b.item&&b.item.uuis==a});c.resolve(g)}).fail(function(b){c.reject(b)}):c.resolve(g);return c.promise()},k=function(){return D(function(){var a=b(),d=new RegExp(c+"$");rea.storage.sync.get(null,
function(b){var c=[];b&&Object.keys(b).forEach(function(a){-1!=a.search(d)&&c.push({key:a,item:r(b[a],a)})});a.resolve(c)});return a.promise()})},r=function(b,a){var c=null;try{c=JSON.parse(b)}catch(d){}return c&&(c.url||c.options)?c:(l.debug("si: unable to parse extended info of "+a),null)},w=function(a){return a.then(function(a){var c={};a=A.select(a,function(a,b){if(!c[a.key])return c[a.key]=!0});if(1<a.length){var d=b(),e=[],u=a.pop();a.forEach(function(a){e.push(z(a.key))});b.when(e).done(function(){d.resolve(u)});
return d.promise()}return b.Pledge(a[0])})},q=null,h={},z=function(a,c){var d=b();rea.storage.sync.remove(a,function(a){(a=rea.runtime.lastError)?d.reject(a):d.resolve()});return d.promise()},y=function(a){var c=b();rea.storage.sync.set(h,function(a){(a=rea.runtime.lastError)?c.reject(a):(h={},c.resolve())});return c.promise()};return{init:function(){var e=!0;if(!a)try{rea.storage.onChanged.addListener(d),a=!0}catch(h){l.warn("si: error registering sync callback: "+h.message),e=!1}c="@v2";return b.Pledge(e)},
list:function(){return b.Pledge().then(function(){if(null===v)return C()}).then(function(){return k()}).then(function(a){var d=new RegExp(c+"$"),e=[];a.forEach(function(a){var b=a.key,c=a.item;a=b.replace(d,"");var f=null;if(f=h[b]?r(h[b],b):c)b=f.options||{},c=!!b.removed,e.push({id:a,uuid:c?a:f.uuid,lastModified:c?b.removed:f.lastModified,url:f.url,options:b})});return b.Pledge(e)})},setMeta:function(a,d){var g=b();w(e(a.uuid)).done(function(b){var e;b?(e=b.key,b=b.item):(e=a.uuid+c,b={});b.url=
a.url;b.options=a.options||{};b.uuid=a.uuid;d.lastModified&&(b.lastModified=d.lastModified);h[e]=JSON.stringify(b);q&&window.clearTimeout(q);q=window.setTimeout(y,3E3);g.resolve()});return g.promise()},remove:function(a){var d=b();w(e(a.uuid)).done(function(b){var e;b?(e=b.key,b=b.item):(e=a.uuid+c,b={});b.options=b.options||{};b.options.removed=Date.now()+v;h[e]=JSON.stringify(b);q&&window.clearTimeout(q);q=window.setTimeout(y,3E3);d.resolve()});return d.promise()},reset:function(){return D(function(){var a=
b();rea.storage.sync.clear(function(){h={};a.resolve()});return a.promise()})}}}(),e={};rea.storage.sync.supported&&(e[t.eCHROMESYNC]=c);e[t.eGDRIVE]=d;e[t.eDROPBOX]=a;return e}(),E=function(){var a=b(),d=0,c=function(){if(d<y.length){var b=y[d];G({method:b.method,url:b.url},{ondone:function(n){4==n.readyState&&200==n.status?(n=b.extract(n.responseText,n.responseHeaders),null===n?(d++,window.setTimeout(c,1)):a.resolve(n)):(d++,window.setTimeout(c,1))}})}else a.reject(void 0)};c();return a.promise()},
C=function(){var a=b();E().done(function(a){v=a.getTime()-Date.now()}).fail(function(){v=0;l.log("si: time offset detection failed!")}).always(a.resolve);return a.promise()},D=function(a,d){var c=b();void 0===d&&(d=3);var e=function(){if(r)window.setTimeout(e,500);else{r=!0;try{a().always(function(){r=!1}).done(function(){c.resolve.apply(this,arguments)}).fail(function(){0<--d?(l.log("si: some retries left, wait for",6E4,"ms"),window.setTimeout(e,6E4)):(l.warn("si: no retries left, skipping this sync request!"),
c.reject("no retries left"))})}catch(b){l.warn(b),r=!1,c.reject(b)}}};e();return c.promise()},F={init:function(a){x=[];m=a;return k[m]?k[m].init().done(function(a){}):b.Breach()},getUtc:E,debug:function(a){},addChangeListener:function(a){x.push(a)},caps:function(){var a={};a.__defineGetter__("specialMeta",function(){return k[m]&&!!k[m].getMeta});a.__defineGetter__("syncsSource",function(){return k[m]&&!!k[m].getSource});return a}(),types:t};"list setMeta getMeta setSource getSource reset remove".split(" ").forEach(function(a){F[a]=
function(){return k[m]&&k[m][a]?k[m][a].apply(this,arguments):b.Pledge()}});Registry.register("syncinfo","5770",function(a){w.init(function(d){var c=b(),e=a.openAndWatch({url:d.url},function(a){a?c&&c.notify(a):c&&(c.reject("auth_failed"),c=null)});return{promise:c.promise(),close:function(){e.cancel()}}});return F})});
