'use strict';

require('mocha');

var _chai = require('chai');

var _tagAppender = require('../src/tag-appender');

describe('tag appender', function () {

  beforeEach(function () {
    this.jsdom = require('jsdom-global')();
  });

  afterEach(function () {
    this.jsdom();
  });

  it('should unload css in the right order', function () {
    var cssUrl = 'http://example.com/test.css';
    var css1 = (0, _tagAppender.createLinkElement)(cssUrl);
    var css2 = (0, _tagAppender.createLinkElement)(cssUrl);

    var headElement = document.getElementsByTagName('head')[0];
    headElement.appendChild(css1);
    headElement.appendChild(css2);

    (0, _tagAppender.unloadStyles)(document, [cssUrl]);

    (0, _chai.expect)(document.getElementsByTagName('link').length).to.equal(1);
    (0, _chai.expect)(document.getElementsByTagName('link')[0]).to.equal(css2);
  });

  it('should unload css for files with optional flag', function () {
    var cssUrl = 'http://example.com/test.css';
    var jsUrl = 'http://example.com/test.js';

    var headElement = document.getElementsByTagName('head')[0];
    headElement.appendChild((0, _tagAppender.createLinkElement)(cssUrl));
    headElement.appendChild((0, _tagAppender.createLinkElement)(jsUrl));

    var link1 = { url: cssUrl, optional: true };
    var link2 = { url: jsUrl, optional: true };

    (0, _tagAppender.unloadStyles)(document, [link1, link2]);

    (0, _chai.expect)(document.getElementsByTagName('link').length).to.equal(1);
  });

  it('filesAppender should set optional flag to false by default', function (done) {
    var link1 = { url: 'http://123.js/' };
    var link2 = { url: 'http://456.js/' };

    (0, _tagAppender.filesAppender)([link1, link2]).catch(function () {
      return done();
    });
    setTimeout(function () {
      document.getElementsByTagName('script')[0].onerror();
    }, 100);
  }).timeout(1000);

  it('filesAppender should support optional flag', function (done) {
    var link1 = { url: 'http://123.js/', optional: true };
    var link2 = { url: 'http://456.js/', optional: true };

    (0, _tagAppender.filesAppender)([link1, link2]).then(function () {
      return done();
    });

    setTimeout(function () {
      document.getElementsByTagName('script')[0].onerror();
      document.getElementsByTagName('script')[1].onerror();
    }, 100);
  }).timeout(1000);
});