<commit_before>'use strict';

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var MediaPage = process.requirePublish('tests/client/e2eTests/pages/MediaPage.js');
var VideoModel = process.requirePublish('app/server/models/VideoModel.js');
var MediaHelper = process.requirePublish('tests/client/e2eTests/helpers/MediaHelper.js');
var datas = process.requirePublish('tests/client/e2eTests/resources/data.json');

// Load assertion library
var assert = chai.assert;
chai.use(chaiAsPromised);

describe('Media page', function() {
  var page, mediaHelper;

  // Prepare page
  before(function() {
    var videoModel = new VideoModel();
    mediaHelper = new MediaHelper(videoModel);
    page = new MediaPage(videoModel);
  });

  // Logout after tests
  after(function() {
    page.logout();
  });

  describe('without access permission', function() {

    // Log with a user without access permission
    before(function() {
      return page.logAs(datas.users.publishGuest);
    });

    it('should not access the page', function() {
      return page.load().then(function() {
        assert.ok(false, 'User has access to medias page and should not');
      }, function() {
        assert.ok(true);
      });
    });

  });

  describe('medias', function() {
    var ownerLineToAdd;
    var anonymousLineToAdd;
    var mediaHelperWithUser;

    before(function() {
      var owner = process.protractorConf.getUser(datas.users.publishMedias1.name);
      var videoModelWithUser = new VideoModel(owner);
      mediaHelperWithUser = new MediaHelper(videoModelWithUser);
    });

    // Log with a user without access permission
    beforeEach(function() {
      anonymousLineToAdd = {
        id: '0',
        state: VideoModel.PUBLISHED_STATE,
        title: 'Media 1',
        description: 'Media 1 description'
      };

      ownerLineToAdd = {
        id: '1',
        state: VideoModel.PUBLISHED_STATE,
        title: 'Media 2',
        description: 'Media 2 description',
        groups: ['publishGroup1']
      };

      mediaHelper.addEntities([anonymousLineToAdd]);
      return mediaHelperWithUser.addEntities([ownerLineToAdd]);
    });

    // Remove all medias after each tests then reload the page
    afterEach(function() {
      mediaHelper.removeAllEntities();
    });

    describe('access', function() {

      it('should be able by the owner', function() {
        page.logAs(datas.users.publishMedias1);
        page.load();
        assert.isFulfilled(page.getLine(anonymousLineToAdd.title), 'Expected media ' + anonymousLineToAdd.title);
        assert.isFulfilled(page.getLine(ownerLineToAdd.title), 'Expected media ' + ownerLineToAdd.title);

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be accessible');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be accessible');
        });
      });

      it('should be able by the super administrator', function() {
        page.logAsAdmin();
        page.load();
        assert.isFulfilled(page.getLine(anonymousLineToAdd.title), 'Expected media ' + anonymousLineToAdd.title);
        assert.isFulfilled(page.getLine(ownerLineToAdd.title), 'Expected media ' + ownerLineToAdd.title);

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be accessible');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be accessible');
        });
      });

      it('should be able by users in the group', function() {
        page.logAs(datas.users.publishMediasGroup);
        page.load();
        assert.isFulfilled(page.getLine(anonymousLineToAdd.title), 'Expected media ' + anonymousLineToAdd.title);
        assert.isFulfilled(page.getLine(ownerLineToAdd.title), 'Expected media ' + ownerLineToAdd.title);

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be accessible');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be accessible');
        });
      });

      it('should not be able by users in the group without read permission', function() {
        page.logAs(datas.users.publishMediasGroupNoRead);
        page.load();
        assert.isRejected(page.getLine(ownerLineToAdd.title), 'Unexpected media ' + ownerLineToAdd.title);

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 403, 'Expected video to be inaccessible');
        });
      });

      it('should not be able by other users', function() {
        page.logAs(datas.users.publishMedias2);
        page.load();
        assert.isFulfilled(page.getLine(anonymousLineToAdd.title), 'Expected media ' + anonymousLineToAdd.title);
        assert.isRejected(page.getLine(ownerLineToAdd.title), 'Unexpected media ' + ownerLineToAdd.title);

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be accessible');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 403, 'Expected owner video to be inaccessible');
        });
      });

    });

    describe('edition', function() {

      it('should be able by the owner', function() {
        var ownerLineNewTitle = ownerLineToAdd.title + ' new';
        var anonymousLineNewTitle = anonymousLineToAdd.title + ' new';

        page.logAs(datas.users.publishMedias1);
        page.load();

        assert.isFulfilled(page.editMedia(ownerLineToAdd.title, {
          name: ownerLineNewTitle
        }), 'Expected media ' + ownerLineNewTitle + ' to be editable');

        assert.isFulfilled(page.editMedia(anonymousLineToAdd.title, {
          name: anonymousLineNewTitle
        }), 'Expected media ' + anonymousLineNewTitle + ' to be editable');

        assert.isFulfilled(page.getLine(anonymousLineNewTitle), 'Expected media ' + anonymousLineNewTitle);
        assert.isFulfilled(page.getLine(ownerLineNewTitle), 'Expected media ' + ownerLineNewTitle);

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'post', {
          title: ownerLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be editable');
        });

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'post', {
          title: anonymousLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be editable');
        });
      });

      it('should be able by the super administrator', function() {
        var ownerLineNewTitle = ownerLineToAdd.title + ' new';
        var anonymousLineNewTitle = anonymousLineToAdd.title + ' new';

        page.logAsAdmin();
        page.load();

        assert.isFulfilled(page.editMedia(ownerLineToAdd.title, {
          name: ownerLineNewTitle
        }), 'Expected media ' + ownerLineNewTitle + ' to be editable');

        assert.isFulfilled(page.editMedia(anonymousLineToAdd.title, {
          name: anonymousLineNewTitle
        }), 'Expected media ' + anonymousLineNewTitle + ' to be editable');

        assert.isFulfilled(page.getLine(anonymousLineNewTitle), 'Expected media ' + anonymousLineNewTitle);
        assert.isFulfilled(page.getLine(ownerLineNewTitle), 'Expected media ' + ownerLineNewTitle);

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'post', {
          title: ownerLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be editable');
        });

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'post', {
          title: anonymousLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be editable');
        });

      });

      it('should be able by users in the group', function() {
        var ownerLineNewTitle = ownerLineToAdd.title + ' new';
        page.logAs(datas.users.publishMediasGroup);
        page.load();

        assert.isFulfilled(page.editMedia(ownerLineToAdd.title, {
          name: ownerLineNewTitle
        }), 'Expected media ' + ownerLineNewTitle + ' to be editable');

        assert.isFulfilled(page.getLine(ownerLineNewTitle), 'Expected media ' + ownerLineNewTitle);

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'post', {
          title: ownerLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected video in the group to be editable');
        });
      });

      it('should not be able by other users', function() {
        var ownerLineNewTitle = ownerLineToAdd.title + ' new';
        page.logAs(datas.users.publishMedias2);
        page.load();

        assert.isRejected(page.editMedia(ownerLineToAdd.title, {
          name: ownerLineNewTitle
        }), 'Expected media ' + ownerLineNewTitle + ' not to be editable');

        assert.isRejected(page.getLine(ownerLineNewTitle), 'Unexpected media ' + ownerLineNewTitle);

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'post', {
          title: ownerLineNewTitle
        }).then(function(response) {
          assert.equal(response.status, 403, 'Expected video in the group not to be editable');
        });
      });
    });

    describe('deletion', function() {

      it('should be deletable by the owner', function() {
        page.logAs(datas.users.publishMedias1);
        page.load();

        page.removeLine(ownerLineToAdd.title);
        page.removeLine(anonymousLineToAdd.title);
        assert.isRejected(page.getLine(anonymousLineToAdd.title), 'Unexpected media ' + anonymousLineToAdd.title);
        assert.isRejected(page.getLine(ownerLineToAdd.title), 'Unexpected media ' + ownerLineToAdd.title);
      });

      it('should be able by the owner by calling the server directly', function() {
        page.logAs(datas.users.publishMedias1);
        page.load();

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be deletable');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be deletable');
        });
      });

      it('should be able by the super administrator', function() {
        page.logAsAdmin();
        page.load();

        page.removeLine(ownerLineToAdd.title);
        page.removeLine(anonymousLineToAdd.title);
        assert.isRejected(page.getLine(anonymousLineToAdd.title), 'Unexpected media ' + anonymousLineToAdd.title);
        assert.isRejected(page.getLine(ownerLineToAdd.title), 'Unexpected media ' + ownerLineToAdd.title);
      });

      it('should be able by the administrator by calling the server directly', function() {
        page.logAsAdmin();
        page.load();

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be deletable');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be deletable');
        });
      });

      it('should be able by users in the group', function() {
        page.logAs(datas.users.publishMediasGroup);
        page.load();

        page.removeLine(ownerLineToAdd.title);
        assert.isRejected(page.getLine(ownerLineToAdd.title), 'Unexpected media ' + ownerLineToAdd.title);
      });

      it('should be able by users in the group by calling the server directly', function() {
        page.logAs(datas.users.publishMediasGroup);
        page.load();

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected video in the group to be deletable');
        });
      });

      it('should not be able by other users', function() {
        page.logAs(datas.users.publishMedias2);
        page.load();

        assert.isRejected(page.removeLine(ownerLineToAdd.title));

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 500);
        });
      });
    });

  });

});
<commit_msg>Update end to end tests due to chai-as-promised update<commit_after>'use strict';

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var MediaPage = process.requirePublish('tests/client/e2eTests/pages/MediaPage.js');
var VideoModel = process.requirePublish('app/server/models/VideoModel.js');
var MediaHelper = process.requirePublish('tests/client/e2eTests/helpers/MediaHelper.js');
var datas = process.requirePublish('tests/client/e2eTests/resources/data.json');

// Load assertion library
var assert = chai.assert;
chai.use(chaiAsPromised);

describe('Media page', function() {
  var page, mediaHelper;

  // Prepare page
  before(function() {
    var videoModel = new VideoModel();
    mediaHelper = new MediaHelper(videoModel);
    page = new MediaPage(videoModel);
  });

  // Logout after tests
  after(function() {
    page.logout();
  });

  describe('without access permission', function() {

    // Log with a user without access permission
    before(function() {
      return page.logAs(datas.users.publishGuest);
    });

    it('should not access the page', function() {
      return page.load().then(function() {
        assert.ok(false, 'User has access to medias page and should not');
      }, function() {
        assert.ok(true);
      });
    });

  });

  describe('medias', function() {
    var ownerLineToAdd;
    var anonymousLineToAdd;
    var mediaHelperWithUser;

    before(function() {
      var owner = process.protractorConf.getUser(datas.users.publishMedias1.name);
      var videoModelWithUser = new VideoModel(owner);
      mediaHelperWithUser = new MediaHelper(videoModelWithUser);
    });

    // Log with a user without access permission
    beforeEach(function() {
      anonymousLineToAdd = {
        id: '0',
        state: VideoModel.PUBLISHED_STATE,
        title: 'Media 1',
        description: 'Media 1 description'
      };

      ownerLineToAdd = {
        id: '1',
        state: VideoModel.PUBLISHED_STATE,
        title: 'Media 2',
        description: 'Media 2 description',
        groups: ['publishGroup1']
      };

      mediaHelper.addEntities([anonymousLineToAdd]);
      return mediaHelperWithUser.addEntities([ownerLineToAdd]);
    });

    // Remove all medias after each tests then reload the page
    afterEach(function() {
      mediaHelper.removeAllEntities();
    });

    describe('access', function() {

      it('should be able by the owner', function() {
        page.logAs(datas.users.publishMedias1);
        page.load();
        assert.isFulfilled(page.getLine(anonymousLineToAdd.title), 'Expected media ' + anonymousLineToAdd.title);
        assert.isFulfilled(page.getLine(ownerLineToAdd.title), 'Expected media ' + ownerLineToAdd.title);

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be accessible');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be accessible');
        });
      });

      it('should be able by the super administrator', function() {
        page.logAsAdmin();
        page.load();
        assert.isFulfilled(page.getLine(anonymousLineToAdd.title), 'Expected media ' + anonymousLineToAdd.title);
        assert.isFulfilled(page.getLine(ownerLineToAdd.title), 'Expected media ' + ownerLineToAdd.title);

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be accessible');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be accessible');
        });
      });

      it('should be able by users in the group', function() {
        page.logAs(datas.users.publishMediasGroup);
        page.load();
        assert.isFulfilled(page.getLine(anonymousLineToAdd.title), 'Expected media ' + anonymousLineToAdd.title);
        assert.isFulfilled(page.getLine(ownerLineToAdd.title), 'Expected media ' + ownerLineToAdd.title);

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be accessible');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be accessible');
        });
      });

      it('should not be able by users in the group without read permission', function() {
        page.logAs(datas.users.publishMediasGroupNoRead);
        page.load();
        assert.isRejected(page.getLine(ownerLineToAdd.title));

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 403, 'Expected video to be inaccessible');
        });
      });

      it('should not be able by other users', function() {
        page.logAs(datas.users.publishMedias2);
        page.load();
        assert.isFulfilled(page.getLine(anonymousLineToAdd.title), 'Expected media ' + anonymousLineToAdd.title);
        assert.isRejected(page.getLine(ownerLineToAdd.title));

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be accessible');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'get').then(function(response) {
          assert.equal(response.status, 403, 'Expected owner video to be inaccessible');
        });
      });

    });

    describe('edition', function() {

      it('should be able by the owner', function() {
        var ownerLineNewTitle = ownerLineToAdd.title + ' new';
        var anonymousLineNewTitle = anonymousLineToAdd.title + ' new';

        page.logAs(datas.users.publishMedias1);
        page.load();

        assert.isFulfilled(page.editMedia(ownerLineToAdd.title, {
          name: ownerLineNewTitle
        }), 'Expected media ' + ownerLineNewTitle + ' to be editable');

        assert.isFulfilled(page.editMedia(anonymousLineToAdd.title, {
          name: anonymousLineNewTitle
        }), 'Expected media ' + anonymousLineNewTitle + ' to be editable');

        assert.isFulfilled(page.getLine(anonymousLineNewTitle), 'Expected media ' + anonymousLineNewTitle);
        assert.isFulfilled(page.getLine(ownerLineNewTitle), 'Expected media ' + ownerLineNewTitle);

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'post', {
          title: ownerLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be editable');
        });

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'post', {
          title: anonymousLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be editable');
        });
      });

      it('should be able by the super administrator', function() {
        var ownerLineNewTitle = ownerLineToAdd.title + ' new';
        var anonymousLineNewTitle = anonymousLineToAdd.title + ' new';

        page.logAsAdmin();
        page.load();

        assert.isFulfilled(page.editMedia(ownerLineToAdd.title, {
          name: ownerLineNewTitle
        }), 'Expected media ' + ownerLineNewTitle + ' to be editable');

        assert.isFulfilled(page.editMedia(anonymousLineToAdd.title, {
          name: anonymousLineNewTitle
        }), 'Expected media ' + anonymousLineNewTitle + ' to be editable');

        assert.isFulfilled(page.getLine(anonymousLineNewTitle), 'Expected media ' + anonymousLineNewTitle);
        assert.isFulfilled(page.getLine(ownerLineNewTitle), 'Expected media ' + ownerLineNewTitle);

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'post', {
          title: ownerLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be editable');
        });

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'post', {
          title: anonymousLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be editable');
        });

      });

      it('should be able by users in the group', function() {
        var ownerLineNewTitle = ownerLineToAdd.title + ' new';
        page.logAs(datas.users.publishMediasGroup);
        page.load();

        assert.isFulfilled(page.editMedia(ownerLineToAdd.title, {
          name: ownerLineNewTitle
        }), 'Expected media ' + ownerLineNewTitle + ' to be editable');

        assert.isFulfilled(page.getLine(ownerLineNewTitle), 'Expected media ' + ownerLineNewTitle);

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'post', {
          title: ownerLineToAdd.title
        }).then(function(response) {
          assert.equal(response.status, 200, 'Expected video in the group to be editable');
        });
      });

      it('should not be able by other users', function() {
        var ownerLineNewTitle = ownerLineToAdd.title + ' new';
        page.logAs(datas.users.publishMedias2);
        page.load();

        assert.isRejected(page.editMedia(ownerLineToAdd.title, {
          name: ownerLineNewTitle
        }));

        assert.isRejected(page.getLine(ownerLineNewTitle));

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'post', {
          title: ownerLineNewTitle
        }).then(function(response) {
          assert.equal(response.status, 403, 'Expected video in the group not to be editable');
        });
      });
    });

    describe('deletion', function() {

      it('should be deletable by the owner', function() {
        page.logAs(datas.users.publishMedias1);
        page.load();

        page.removeLine(ownerLineToAdd.title);
        page.removeLine(anonymousLineToAdd.title);
        assert.isRejected(page.getLine(anonymousLineToAdd.title));
        assert.isRejected(page.getLine(ownerLineToAdd.title));
      });

      it('should be able by the owner by calling the server directly', function() {
        page.logAs(datas.users.publishMedias1);
        page.load();

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be deletable');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be deletable');
        });
      });

      it('should be able by the super administrator', function() {
        page.logAsAdmin();
        page.load();

        page.removeLine(ownerLineToAdd.title);
        page.removeLine(anonymousLineToAdd.title);
        assert.isRejected(page.getLine(anonymousLineToAdd.title));
        assert.isRejected(page.getLine(ownerLineToAdd.title));
      });

      it('should be able by the administrator by calling the server directly', function() {
        page.logAsAdmin();
        page.load();

        page.sendRequest('be/publish/videos/' + anonymousLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected anonymous video to be deletable');
        });

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected owner video to be deletable');
        });
      });

      it('should be able by users in the group', function() {
        page.logAs(datas.users.publishMediasGroup);
        page.load();

        page.removeLine(ownerLineToAdd.title);
        assert.isRejected(page.getLine(ownerLineToAdd.title));
      });

      it('should be able by users in the group by calling the server directly', function() {
        page.logAs(datas.users.publishMediasGroup);
        page.load();

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 200, 'Expected video in the group to be deletable');
        });
      });

      it('should not be able by other users', function() {
        page.logAs(datas.users.publishMedias2);
        page.load();

        assert.isRejected(page.removeLine(ownerLineToAdd.title));

        page.sendRequest('be/publish/videos/' + ownerLineToAdd.id, 'delete').then(function(response) {
          assert.equal(response.status, 500);
        });
      });
    });

  });

});
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var itemTypes = require('./itemTypes');
var ships = require('./ships');
var upgrades = require('../models/upgrades').all;
var pilots = require('../models/pilots').allRebels;

var XpItem = function (upgradeType, data) {
    this.upgradeType = upgradeType;
    this.data = data;
};

XpItem.prototype.cost = function () {
    if (this.upgradeType === itemTypes.SHIP_TYPE) {
        return -5;
    } else if (this.upgradeType === itemTypes.STARTING_SHIP_TYPE) {
        var startingShip = this.getShipById(this.data.shipId);
        return startingShip.startingXp;
    } else if (this.upgradeType === itemTypes.PILOT_SKILL) {
        // pilot skill costs double skill level upgrading to
        return (this.data.pilotSkill * 2) * -1;
    } else if (this.upgradeType === itemTypes.MISSION) {
        return this.data.missionXp;
    } else if (this.upgradeType === itemTypes.BUY_UPGRADE) {
        var upgrade = this.getUpgradeById(this.data.upgradeId);
        if (upgrade.points === 0) {
            return 0
        }
        return upgrade.points * -1;
    } else if (this.upgradeType === itemTypes.BUY_PILOT_ABILITY) {
        var pilot = this.getPilotById(this.data.pilotId);
        return pilot.skill * -1;
    }
    return 0;
};

XpItem.prototype.label = function () {
    if (this.upgradeType === itemTypes.SHIP_TYPE) {
        var ship = this.getShipById(this.data.shipId);
        return 'Change ship: ' + ship.label;
    } else if (this.upgradeType === itemTypes.STARTING_SHIP_TYPE) {
        var startingShip = this.getShipById(this.data.shipId);
        return 'Starting ship: ' + startingShip.label;
    } else if (this.upgradeType === itemTypes.PILOT_SKILL) {
        return 'Upgrade pilot skill: PS ' + this.data.pilotSkill;
    } else if (this.upgradeType === itemTypes.MISSION) {
        return 'Gain mission XP';
    } else if (this.upgradeType === itemTypes.BUY_UPGRADE) {
        var upgrade = this.getUpgradeById(this.data.upgradeId);
        return upgrade.slot + ': ' + upgrade.name;
    } else if (this.upgradeType === itemTypes.BUY_PILOT_ABILITY) {
        var pilot = this.getPilotById(this.data.pilotId);
        return 'Pilot Ability: ' + pilot.name;
    }
    return '';
};

XpItem.prototype.exportString = function () {
    var idString = '';
    var dataString = '';
    if (this.upgradeType === itemTypes.SHIP_TYPE) {
        dataString = this.data.shipId;
        idString = 'ST';
    } else if (this.upgradeType === itemTypes.STARTING_SHIP_TYPE) {
        dataString = this.data.shipId;
        idString = 'SST';
    } else if (this.upgradeType === itemTypes.PILOT_SKILL) {
        dataString = this.data.pilotSkill;
        idString = 'PS';
    } else if (this.upgradeType === itemTypes.MISSION) {
        dataString = this.data.missionXp;
        idString = 'XP';
    } else if (this.upgradeType === itemTypes.BUY_UPGRADE) {
        dataString = this.data.upgradeId;
        idString = 'UP';
    } else if (this.upgradeType === itemTypes.BUY_PILOT_ABILITY) {
        dataString = this.data.pilotId;
        idString = 'PA';
    }
    return idString + '=' + dataString;
};

XpItem.prototype.parseExportString = function (exportString) {
    var splitItems = exportString.split('=');
    var idString = splitItems[0];
    var dataString = splitItems[1];
    this.data = {};

    if (idString === 'SST') {
        this.data.shipId = dataString;
        this.upgradeType = itemTypes.STARTING_SHIP_TYPE;
    } else if (idString === 'ST') {
        this.data.shipId = dataString;
        this.upgradeType = itemTypes.SHIP_TYPE;
    } else if (idString === 'PS') {
        this.data.pilotSkill = parseInt(dataString, 10);
        this.upgradeType = itemTypes.PILOT_SKILL;
    } else if (idString === 'XP') {
        this.data.missionXp = parseInt(dataString, 10);
        this.upgradeType = itemTypes.MISSION;
    } else if (idString === 'UP') {
        this.data.upgradeId = parseInt(dataString, 10);
        this.upgradeType = itemTypes.BUY_UPGRADE;
    } else if (idString === 'PA') {
        this.data.pilotId = parseInt(dataString, 10);
        this.upgradeType = itemTypes.BUY_PILOT_ABILITY;
    }
};

XpItem.prototype.getShipById = function (shipId) {
    return _.find(ships, function (shipItem) {
        return shipItem.id === shipId;
    });
};

XpItem.prototype.getUpgradeById = function (upgradeId) {
    return _.find(upgrades, function (upgradeItem) {
        return upgradeItem.id === upgradeId;
    });
};

XpItem.prototype.getPilotById = function (pilotId) {
    return _.find(pilots, function (pilotCard) {
        return pilotCard.id === pilotId;
    });
};

module.exports = XpItem;

<commit_msg>fix lint error<commit_after>'use strict';

var _ = require('lodash');
var itemTypes = require('./itemTypes');
var ships = require('./ships');
var upgrades = require('../models/upgrades').all;
var pilots = require('../models/pilots').allRebels;

var XpItem = function (upgradeType, data) {
    this.upgradeType = upgradeType;
    this.data = data;
};

XpItem.prototype.cost = function () {
    if (this.upgradeType === itemTypes.SHIP_TYPE) {
        return -5;
    } else if (this.upgradeType === itemTypes.STARTING_SHIP_TYPE) {
        var startingShip = this.getShipById(this.data.shipId);
        return startingShip.startingXp;
    } else if (this.upgradeType === itemTypes.PILOT_SKILL) {
        // pilot skill costs double skill level upgrading to
        return (this.data.pilotSkill * 2) * -1;
    } else if (this.upgradeType === itemTypes.MISSION) {
        return this.data.missionXp;
    } else if (this.upgradeType === itemTypes.BUY_UPGRADE) {
        var upgrade = this.getUpgradeById(this.data.upgradeId);
        if (upgrade.points === 0) {
            return 0;
        }
        return upgrade.points * -1;
    } else if (this.upgradeType === itemTypes.BUY_PILOT_ABILITY) {
        var pilot = this.getPilotById(this.data.pilotId);
        return pilot.skill * -1;
    }
    return 0;
};

XpItem.prototype.label = function () {
    if (this.upgradeType === itemTypes.SHIP_TYPE) {
        var ship = this.getShipById(this.data.shipId);
        return 'Change ship: ' + ship.label;
    } else if (this.upgradeType === itemTypes.STARTING_SHIP_TYPE) {
        var startingShip = this.getShipById(this.data.shipId);
        return 'Starting ship: ' + startingShip.label;
    } else if (this.upgradeType === itemTypes.PILOT_SKILL) {
        return 'Upgrade pilot skill: PS ' + this.data.pilotSkill;
    } else if (this.upgradeType === itemTypes.MISSION) {
        return 'Gain mission XP';
    } else if (this.upgradeType === itemTypes.BUY_UPGRADE) {
        var upgrade = this.getUpgradeById(this.data.upgradeId);
        return upgrade.slot + ': ' + upgrade.name;
    } else if (this.upgradeType === itemTypes.BUY_PILOT_ABILITY) {
        var pilot = this.getPilotById(this.data.pilotId);
        return 'Pilot Ability: ' + pilot.name;
    }
    return '';
};

XpItem.prototype.exportString = function () {
    var idString = '';
    var dataString = '';
    if (this.upgradeType === itemTypes.SHIP_TYPE) {
        dataString = this.data.shipId;
        idString = 'ST';
    } else if (this.upgradeType === itemTypes.STARTING_SHIP_TYPE) {
        dataString = this.data.shipId;
        idString = 'SST';
    } else if (this.upgradeType === itemTypes.PILOT_SKILL) {
        dataString = this.data.pilotSkill;
        idString = 'PS';
    } else if (this.upgradeType === itemTypes.MISSION) {
        dataString = this.data.missionXp;
        idString = 'XP';
    } else if (this.upgradeType === itemTypes.BUY_UPGRADE) {
        dataString = this.data.upgradeId;
        idString = 'UP';
    } else if (this.upgradeType === itemTypes.BUY_PILOT_ABILITY) {
        dataString = this.data.pilotId;
        idString = 'PA';
    }
    return idString + '=' + dataString;
};

XpItem.prototype.parseExportString = function (exportString) {
    var splitItems = exportString.split('=');
    var idString = splitItems[0];
    var dataString = splitItems[1];
    this.data = {};

    if (idString === 'SST') {
        this.data.shipId = dataString;
        this.upgradeType = itemTypes.STARTING_SHIP_TYPE;
    } else if (idString === 'ST') {
        this.data.shipId = dataString;
        this.upgradeType = itemTypes.SHIP_TYPE;
    } else if (idString === 'PS') {
        this.data.pilotSkill = parseInt(dataString, 10);
        this.upgradeType = itemTypes.PILOT_SKILL;
    } else if (idString === 'XP') {
        this.data.missionXp = parseInt(dataString, 10);
        this.upgradeType = itemTypes.MISSION;
    } else if (idString === 'UP') {
        this.data.upgradeId = parseInt(dataString, 10);
        this.upgradeType = itemTypes.BUY_UPGRADE;
    } else if (idString === 'PA') {
        this.data.pilotId = parseInt(dataString, 10);
        this.upgradeType = itemTypes.BUY_PILOT_ABILITY;
    }
};

XpItem.prototype.getShipById = function (shipId) {
    return _.find(ships, function (shipItem) {
        return shipItem.id === shipId;
    });
};

XpItem.prototype.getUpgradeById = function (upgradeId) {
    return _.find(upgrades, function (upgradeItem) {
        return upgradeItem.id === upgradeId;
    });
};

XpItem.prototype.getPilotById = function (pilotId) {
    return _.find(pilots, function (pilotCard) {
        return pilotCard.id === pilotId;
    });
};

module.exports = XpItem;

<|endoftext|>


<commit_before>import {
  PROFILE_NOW,
  PROFILE_THEN
} from 'containers/HomePage/constants';

export const about_me = {
  [PROFILE_NOW] : {
    summary: `As a full Stack Web Developer who bases in the Bay Area and recently graduated
              with an Associate Degree in Computer Science from De Anza College, I have been
              building more than 20 small-to-intermediate-size projects with jQuery, React,
              D3, mongoDB, Express and SCSS for almost 2 years. \\br

              I’m looking for a job that I am passionate about and will help me improve my skills
              on programming, communication and teamwork. I’m also seeking for the
              opportunity to learn new skills for future use.`,

    skills : {
      'Languages and Skills': {
        JavaScript: `I started learning JavaScript in 2015 with freeCodeCamp. So far, I have built several
                    intermediate-size web apps using JavaScript, mostly with frameworks and libraries like
                    jQuery and React. I'm not quite strong in basic JavaScript but I know enough concepts to
                    get by, like closure, prototypal inheritant, functional programming, arrow function,compose,
                    and curry. The most important thing is I'm still learning and I know where to look for the
                    knowledge that I forget or don't know yet.`,
        'Node.js' : `I learned Node indirectly through setting up and installing dependencies for React projects
                    as well as using webpack for packing. I also built several simple API servers for my web apps
                    using Node. I read "Node.js in Action" and found many interesting ideas in the book but I haven't
                    had the change to practice them yet.`,
        HTML:  `I started learning HTML about the same time with learning JavaScript, which is in 2015. Since my
                main focus is JavaScript, I learned pretty well how to manipulate HTML elements, like body, div,
                span, p, br, h1, h2 etc., through JavaScript.`,
        CSS:    `Until now, I only know CSS enough to decorate my web apps in a basic sense. I know some basic
                CSS properties like height, width, position, margin, padding, opacity, z-index and the like.
                However, I still don't know throughfully about some tricky properties like transform, translate.
                I don't know much about either web lay-out design or color scheme. But I'm not a web designer after all.
                However, the more I work on web apps, the more I discover how much I can do with CSS to achieve my goal
                without JavaScript and as the result, the more I'm interested in CSS. I'm still learning and experimenting
                CSS.`
      },

      Database: {
        mongoDB: `MongoDB basically is a huge hashtable but it's so convienent because of its familiar json-like structure.
                  I haven't worked much with MongoDB, only in 3 or 4 apps that I built from front end to back end. However,
                  as a JavaScript developer, json is my friend. So I don't think mongoDB can make me feel uncomfortable.`
      },

      'Frameworks/Libraries': {
        React: `This is my favorite framework. The idea of combining HTML and JavaScript in one place is a huge innovative idea.
                Before React, I always felt that my apps were like a mess with HTML in this side and JavaScript in another side.
                Moreover, I come from a Object-Oriented Programming background. Before JavaScript, I had learned Java at school,
                a programming language in which everything is a class. Indeed, there's class in JavaScript but it's not technically
                the kind of class in Java. There is no private variable or private method. They are only something that we create
                'artificially' with closure. My code became more and more like spaghetti code as it grew and it made me uncomfortable.
                I couldn't arrange it into class like in Java. But then, React came and saved the day. Now I can organize
                my web apps nicely into class or component, just like the good old days with Java. Ever since, every web app I wrote is
                built upon on React framework.`,

        Redux: `Unfortunately, life is not as good as a dream. Even though React helps me tremendously in building web app, the more complex
                the app is, the more I see my code tangled with React's states that are wired altogether and all over the place. And then, I
                learned Redux. Suddenly, I felt like all of 'the wires' are tied together into a buddle, then placed and distributed neatly
                everywhere in the apps.`,

        Saga: `To be honest, saga is new to me. And the concepts of 'yield' and 'generator' are, to me, not only new. They're eye-openning. It
                looks like magic when you can code async functions and your code is still like sync function that and you can read it easily
                in the familiar top-to-bottom order. I know there is more to it, other than getting and sending data and I'm still experimenting it.`,

        D3: `I know D3 is used mainly for data visualization but I haven't used it much for its main purpose. So far, I only used it to draw two or
            three basic graphs to finish my freeCodeCamp program. Instead, I used it mostly for animation in most of my web apps because it's easy and
            it's convenient. But I know using a giant framework to only move a div from one place to another is ridiculous. That's why recently, I tried to
            use basic JavaScript for those tasks. I'll learn more about D3 and its capacity.`,

        jQuery: `So far, I only used jQuery for 6 or 7 months in total when following freeCodeCamp. And then, after learning React and
                falling in love with it, I abandoned jQuery altogether. I know it's not fair for jQuery. But I don't want to use two
                frameworks in one app. It's overkill. And moreover, I can't see what jQuery can do that React and basic JavaScript can not do.`,

        SCSS: `I had worked with SCSS for quite a long time and feel very comfortable with it. However, since the time I knew about
                styled-components, I have never came back to SCSS.`,

        'Express.js': `I have used Express to build the backend of several apps. They are not too big but only small API servers. My
                      experience with Express so far just involves search and apply. In other word, I search and then read enough to solve
                      the problem at hand. I haven't read or dig deeper into it.`
      },

      Others: {
        Java: `This is my favorite language, only after JavaScript, of course. It is because of Java, I think and code everything in class.
                However, I do not have work experience with Java. I learned Java in college. `,
        'C++': ``,
        Assembly: ``
      }
    }
  },
  [PROFILE_THEN] : {
    summary: `Back in VietNam, I was a radiologist. After graduate from medical school in 2007,
              I continued to study to get a certificate in abdomen ultrasonography and then have been working
              for 3 years as a radiologist in Nguyen Trai Hospital. But then, I felt my career would lead
              to nowhere if I continued. So, I quit my job and went to the U.S to follow my passion since
              I was a kid, which is computer science. \\br

              I'm also the founder and administrator of one of the first online medical forum in VietNam for
              seven years, from 2002 to 2009.`,
    skills: {
      Ultrasound: {
          Abdomen: `I have three years experience in performing abdominal ultrasound examination in Nguyen Trai
                    Hospital. It includes performing the exam on patients and giving image diagnosis on abdominal
                    diseases, like hepatitis, cirrhosis, pancreatitis, and especially appendicitis. My work also
                    includes detecting abdominal cancers in their early stages.`,

          Pelvic:  `Although I did not perform as much as abdominal ultrasound examination, I also have three years
                    experience in performing pelvic ultrasound examination in Nguyen Trai Hospital. I can give image
                    diagnosis on and detect gynecological diseases like cancer and pre-cancerous diseases of the female
                    reproductive organ, uterine fibroids, endometriosis, and adenomyosis.`,

          Pregnancy: ``,

          Thyroid: ``,

          'Soft Tissue': ``
      },

      Webmaster: {
        'Invision Power Board' : ``,
        PHP: ``,
        MySQL: ``,
        Administrator: ``
      }
    }
  }
}

/*
'Perform ultrasonography examination on patients, including abdominal, pelvic, breast, and thyroid ultrasound',
'Give professional opinion on ultrasound images to clinical physicians',
'Provide image diagnosis on abdominal, pelvic, breast, and thyroid diseases with the assist of ultrasound'
*/
<commit_msg>Finish skills on Comp Sci<commit_after>import {
  PROFILE_NOW,
  PROFILE_THEN
} from 'containers/HomePage/constants';

export const about_me = {
  [PROFILE_NOW] : {
    summary: `As a full Stack Web Developer who bases in the Bay Area and recently graduated
              with an Associate Degree in Computer Science from De Anza College, I have been
              building more than 20 small-to-intermediate-size projects with jQuery, React,
              D3, mongoDB, Express and SCSS for almost 2 years. \\br

              I’m looking for a job that I am passionate about and will help me improve my skills
              on programming, communication and teamwork. I’m also seeking for the
              opportunity to learn new skills for future use.`,

    skills : {
      'Languages and Skills': {
        JavaScript: `I started learning JavaScript in 2015 with freeCodeCamp. So far, I have built several
                    intermediate-size web apps using JavaScript, mostly with frameworks and libraries like
                    jQuery and React. I'm not quite strong in basic JavaScript but I know enough concepts to
                    get by, like closure, prototypal inheritant, functional programming, arrow function,compose,
                    and curry. The most important thing is I'm still learning and I know where to look for the
                    knowledge that I forget or don't know yet.`,
        'Node.js' : `I learned Node indirectly through setting up and installing dependencies for React projects
                    as well as using webpack for packing. I also built several simple API servers for my web apps
                    using Node. I read "Node.js in Action" and found many interesting ideas in the book but I haven't
                    had the change to practice them yet.`,
        HTML:  `I started learning HTML about the same time with learning JavaScript, which is in 2015. Since my
                main focus is JavaScript, I learned pretty well how to manipulate HTML elements, like body, div,
                span, p, br, h1, h2 etc., through JavaScript.`,
        CSS:    `Until now, I only know CSS enough to decorate my web apps in a basic sense. I know some basic
                CSS properties like height, width, position, margin, padding, opacity, z-index and the like.
                However, I still don't know throughfully about some tricky properties like transform, translate.
                I don't know much about either web lay-out design or color scheme. But I'm not a web designer after all.
                However, the more I work on web apps, the more I discover how much I can do with CSS to achieve my goal
                without JavaScript and as the result, the more I'm interested in CSS. I'm still learning and experimenting
                CSS.`
      },

      Database: {
        mongoDB: `MongoDB basically is a huge hashtable but it's so convienent because of its familiar json-like structure.
                  I haven't worked much with MongoDB, only in 3 or 4 apps that I built from front end to back end. However,
                  as a JavaScript developer, json is my friend. So I don't think mongoDB can make me feel uncomfortable.`
      },

      'Frameworks/Libraries': {
        React: `This is my favorite framework. The idea of combining HTML and JavaScript in one place is a huge innovative idea.
                Before React, I always felt that my apps were like a mess with HTML in this side and JavaScript in another side.
                Moreover, I come from a Object-Oriented Programming background. Before JavaScript, I had learned Java at school,
                a programming language in which everything is a class. Indeed, there's class in JavaScript but it's not technically
                the kind of class in Java. There is no private variable or private method. They are only something that we create
                'artificially' with closure. My code became more and more like spaghetti code as it grew and it made me uncomfortable.
                I couldn't arrange it into class like in Java. But then, React came and saved the day. Now I can organize
                my web apps nicely into class or component, just like the good old days with Java. Ever since, every web app I wrote is
                built upon on React framework.`,

        Redux: `Unfortunately, life is not as good as a dream. Even though React helps me tremendously in building web app, the more complex
                the app is, the more I see my code tangled with React's states that are wired altogether and all over the place. And then, I
                learned Redux. Suddenly, I felt like all of 'the wires' are tied together into a buddle, then placed and distributed neatly
                everywhere in the apps.`,

        Saga: `To be honest, saga is new to me. And the concepts of 'yield' and 'generator' are, to me, not only new. They're eye-openning. It
                looks like magic when you can code async functions and your code is still like sync function that and you can read it easily
                in the familiar top-to-bottom order. I know there is more to it, other than getting and sending data and I'm still experimenting it.`,

        D3: `I know D3 is used mainly for data visualization but I haven't used it much for its main purpose. So far, I only used it to draw two or
            three basic graphs to finish my freeCodeCamp program. Instead, I used it mostly for animation in most of my web apps because it's easy and
            it's convenient. But I know using a giant framework to only move a div from one place to another is ridiculous. That's why recently, I tried to
            use basic JavaScript for those tasks. I'll learn more about D3 and its capacity.`,

        jQuery: `So far, I only used jQuery for 6 or 7 months in total when following freeCodeCamp. And then, after learning React and
                falling in love with it, I abandoned jQuery altogether. I know it's not fair for jQuery. But I don't want to use two
                frameworks in one app. It's overkill. And moreover, I can't see what jQuery can do that React and basic JavaScript can not do.`,

        SCSS: `I had worked with SCSS for quite a long time and feel very comfortable with it. However, since the time I knew about
                styled-components, I have never came back to SCSS.`,

        'Express.js': `I have used Express to build the backend of several apps. They are not too big but only small API servers. My
                      experience with Express so far just involves search and apply. In other word, I search and then read enough to solve
                      the problem at hand. I haven't read or dig deeper into it.`
      },

      Others: {
        Java: `This is my favorite language, only after JavaScript, of course. It is because of Java, I think and code everything in class.
                However, I do not have work experience with Java. I learned Java in college and coded almost all the problems in the textbook (Introduction
                to Java programming by Daniel Lang). My first coding experience with GUI is with Java. It is because of Java that I appreciate the power of abstract, inheritant and libraries.
                JFrame from the swing library makes creating GUI very simple. Before that, the only language that I knew was C++ and I thought creating a
                window was something very complex and far beyond my knowledge. It was an eye openning experience to me.`,

        'C++': `Around 2014, I learned C++ in college. Two years before that, I'd already self-taught Python. But at the time I took C++, I totally forgot
                everything about Python as well as basic knowledge of programming. So, it's not wrong to say C++ is the first programming language that
                I know. And I'm glad about that. Through C++, I learned many fundamental concepts of programming, like variable, bit and byte manipulation,
                memory, stack and heap, recursion, pointer etc. I also took course in Data Structure using C++. My first experience with LinkedList, Set, BinaryTree,
                Map, Queue, Stack is with C++.`,

        Assembly: `Everyone I know agrees that Assembly is hard. But the funny thing is before taking Assembly course in college, I thought that it was the easiest language
                because there is not much structure in the core language to learn. Only after taking Assembly Language for X86 Processors, I realized how little that I knew.
                It is because there is not much in the core language that makes it so hard. Everything has to be built from scratch. Unfortunately, my experience with Assembly
                is only confined in the college course I took and in less than 10 programs that I built to finish the course. There's a man who coded for more than 20 years told
                me that I should study more about it as it would help me to understand the basic of programming. It would benefit me in a long term. I always promise myself I will
                come back to Assembly some time in the future. But I still do not have enough time for it.`
      }
    }
  },
  [PROFILE_THEN] : {
    summary: `Back in VietNam, I was a radiologist. After graduate from medical school in 2007,
              I continued to study to get a certificate in abdomen ultrasonography and then have been working
              for 3 years as a radiologist in Nguyen Trai Hospital. But then, I felt my career would lead
              to nowhere if I continued. So, I quit my job and went to the U.S to follow my passion since
              I was a kid, which is computer science. \\br

              I'm also the founder and administrator of one of the first online medical forum in VietNam for
              seven years, from 2002 to 2009.`,
    skills: {
      Ultrasound: {
          Abdomen: `I have three years experience in performing abdominal ultrasound examination in Nguyen Trai
                    Hospital. It includes performing the exam on patients and giving image diagnosis on abdominal
                    diseases, like hepatitis, cirrhosis, pancreatitis, and especially appendicitis. My work also
                    includes detecting abdominal cancers in their early stages.`,

          Pelvic:  `Although I did not perform as much as abdominal ultrasound examination, I also have three years
                    experience in performing pelvic ultrasound examination in Nguyen Trai Hospital. I can give image
                    diagnosis on and detect gynecological diseases like cancer and pre-cancerous diseases of the female
                    reproductive organ, uterine fibroids, endometriosis, and adenomyosis.`,

          Pregnancy: `I did not work with `,

          Thyroid: ``,

          'Soft Tissue': ``
      },

      Webmaster: {
        'Invision Power Board' : ``,
        PHP: ``,
        MySQL: ``,
        Administrator: ``
      }
    }
  }
}

/*
'Perform ultrasonography examination on patients, including abdominal, pelvic, breast, and thyroid ultrasound',
'Give professional opinion on ultrasound images to clinical physicians',
'Provide image diagnosis on abdominal, pelvic, breast, and thyroid diseases with the assist of ultrasound'
*/
<|endoftext|>


<commit_before>function Elevator() {
  // body...
  this.currentFloor = Math.floor((Math.random() * 100) + 1);
  this.startingFloor = Math.floor((this.currentFloor / 5));
  this.child = new Plucky;
  this.player = new Player;
  this.rollcount = 0;
  this.yourtrys = 4;
}

Elevator.prototype.go_up = function () {
  // body...
  this.currentFloor += 1;
};

Elevator.prototype.go_down = function () {
  // body...
  this.currentFloor -= 1;
};

Elevator.prototype.myInfo = function () {
  // body...
  var goal = ['Goal: You are trying to get to floor', this.player.desiredFloor].join(" ");
  var start = ['You are on the', this.currentFloor, 'floor'].join(" ");

  document.getElementById('results').innerHTML = [goal, start].join("
");
};

Elevator.prototype.roll = function () {
  // body...
  this.rollcount += 1;
  this.diff = Math.abs(this.currentFloor - this.player.desiredFloor);

  if(this.rollcount == this.yourtrys){
    var mytest = Math.abs(this.diff - this.rollcount);
    var plucky = '
My turn! not your turn! my turn! I push the button!';
    var plucky2 = 'My elalator! not your elalator, my elalator.
'
    var results = ('Sorry. You died of starvation.');
    var test = ['Your current floor was:', this.currentFloor].join(" ");
  document.getElementById('results').innerHTML = [plucky, plucky2, results, test].join("
");
    document.getElementById('roll').disabled = true;
  }
  else
    if (this.currentFloor != this.player.desiredFloor && this.player.desiredFloor > this.currentFloor) {
      this.child.reroll();
      for (var i = 0; i < this.diff / 2; i++) {
        this.calculateCurrentFloor();
      }
      for (var i = 0; i < this.player.wins; i++) {
        this.currentFloor += 1;
        var floor = this.currentFloor;
        var str = 'Floor:';
        document.getElementById('floor').innerHTML = [str, floor].join(" ");
        if (this.currentFloor == this.player.desiredFloor){
          var results = 'The player has won!';
          document.getElementById('roll').disabled = true;
          document.getElementById('winner').innerHTML = [results];
          break;
        }
        this.myInfo();
      }

  } else if (this.currentFloor != this.player.desiredFloor &&  this.player.desiredFloor < this.currentFloor) {
      this.child.reroll();
      for (var i = 0; i < this.diff / 2; i++) {
        this.calculateCurrentFloor();
      }
      for (var i = 0; i < this.player.wins; i++) {
        this.currentFloor -= 1;
        var floor = this.currentFloor;
        var str = 'Floor:';
        document.getElementById('floor').innerHTML = [str, floor].join(" ");
        if (this.currentFloor == this.player.desiredFloor){
          var results = 'The player has won!';
          document.getElementById('roll').disabled = true;
          document.getElementById('winner').innerHTML = [results];
          break;
        }
        this.myInfo();
      }

  } else if(this.currentFloor == this.player.desiredFloor){
      var results = 'The player has won!';
      document.getElementById('roll').disabled = true;
      document.getElementById('winner').innerHTML = [results];
  }

};
Elevator.prototype.calculateCurrentFloor = function () {
  // body...
  this.child.reroll();
  if (this.child.chanceOfPushingButton > 60) {
    this.child.wins += 1;
  } else {
    this.player.wins += 1;
  }
};

function Player(number){
  this.desiredFloor = Math.floor(Math.random() * 100 + 1);
  this.wins = 0;
};

function Plucky(){
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
  this.wins = 0;
};

Plucky.prototype.reroll = function () {
  // body...
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
};

function play(){
document.getElementById('results').innerHTML = ' ';
document.getElementById('floor').innerHTML = " ";
document.getElementById('winner').innerHTML = " ";
game = new Elevator();
game.myInfo();
document.getElementById('roll').disabled = false;
};

function roll(){
  game.roll();
};
<commit_msg>refactor code<commit_after>function Elevator() {
  // body...
  this.currentFloor = Math.floor((Math.random() * 100) + 1);
  this.startingFloor = Math.floor((this.currentFloor / 5));
  this.child = new Plucky;
  this.player = new Player;
  this.rollCount = 0;
  this.numOfTries = 4;
}

Elevator.prototype.go_up = function () {
  // body...
  this.currentFloor += 1;
};

Elevator.prototype.go_down = function () {
  // body...
  this.currentFloor -= 1;
};

Elevator.prototype.elevatorInfo = function () {
  // body...
  var goal = ['Goal: You are trying to get to floor', this.player.desiredFloor].join(" ");
  var start = ['You are on the', this.currentFloor, 'floor'].join(" ");

  document.getElementById('results').innerHTML = [goal, start].join("
");
};

Elevator.prototype.roll = function () {
  // body...
  this.rollCount += 1;
  this.floorDifference = Math.abs(this.currentFloor - this.player.desiredFloor);

  if(this.rollCount == this.numOfTries){
    var plucky = '
My turn! not your turn! my turn! I push the button!';
    var plucky2 = 'My elalator! not your elalator, my elalator.
'
    var result = ('Sorry. You died of starvation.');
    var currentStatus = ['Your current floor was:', this.currentFloor].join(" ");
  document.getElementById('results').innerHTML = [plucky, plucky2, result, currentStatus].join("
");
    document.getElementById('roll').disabled = true;
  }
  else
    if (this.currentFloor != this.player.desiredFloor && this.player.desiredFloor > this.currentFloor) {
      this.child.reroll();
      for (var i = 0; i < this.floorDifference / 2; i++) {
        this.calculateCurrentFloor();
      }
      for (var i = 0; i < this.player.wins; i++) {
        this.currentFloor += 1;
        var floor = this.currentFloor;
        var str = 'Floor:';
        document.getElementById('floor').innerHTML = [str, floor].join(" ");
        if (this.currentFloor == this.player.desiredFloor){
          var result = 'The player has won!';
          document.getElementById('roll').disabled = true;
          document.getElementById('winner').innerHTML = [result];
          break;
        }
        this.elevatorInfo();
      }

  } else if (this.currentFloor != this.player.desiredFloor &&  this.player.desiredFloor < this.currentFloor) {
      this.child.reroll();
      for (var i = 0; i < this.floorDifference / 2; i++) {
        this.calculateCurrentFloor();
      }
      for (var i = 0; i < this.player.wins; i++) {
        this.currentFloor -= 1;
        var floor = this.currentFloor;
        var str = 'Floor:';
        document.getElementById('floor').innerHTML = [str, floor].join(" ");
        if (this.currentFloor == this.player.desiredFloor){
          var result = 'The player has won!';
          document.getElementById('roll').disabled = true;
          document.getElementById('winner').innerHTML = [result];
          break;
        }
        this.elevatorInfo();
      }

  } else if(this.currentFloor == this.player.desiredFloor){
      var results = 'The player has won!';
      document.getElementById('roll').disabled = true;
      document.getElementById('winner').innerHTML = [results];
  }

};
Elevator.prototype.calculateCurrentFloor = function () {
  // body...
  this.child();
  if (this.child.chanceOfPushingButton < 60) {
    this.player.wins += 1;
  }
};

function Player(number){
  this.desiredFloor = Math.floor(Math.random() * 100 + 1);
  this.wins = 0;
};

function Plucky(){
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
};

Plucky.prototype.reroll = function () {
  // body...
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
};

function play(){
document.getElementById('results').innerHTML = ' ';
document.getElementById('floor').innerHTML = " ";
document.getElementById('winner').innerHTML = " ";
game = new Elevator();
game.elevatorInfo();
document.getElementById('roll').disabled = false;
};

function roll(){
  game.roll();
};
<|endoftext|>


<commit_before>import React from 'react';
import FocusTrap from 'focus-trap-react';
import { Container, Modal, Segment } from 'semantic-ui-react';
let fileSaver = require('../../custom_modules/fabricjs/fileSaver');

const headerStyle = {
    'textAlign': 'center'
};

const canvasStyle = {
    'height': '0px',
    'width': '0px',
    'border': '1px solid #000000'
};

class PaintModal extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            modalOpen: false,
            activeTrap: false
        };

        //
        this.reader = new FileReader();
        this.primaryColor = 'black';
        this.secondaryColor = 'black';
        this.drawingMode = false;
        this.canvas = null;

        // For undo - redo
        /*this.canvasState = {
            current: null,
            list: [],
            state: [],
            index: 0,
            index2: 0,
            action: false,
            refresh: true,
        };
*/
        this.objectsStack = [];

        //
        this.handleOpen = this.handleOpen.bind(this);
        this.startFabric = this.startFabric.bind(this);
        this.addRect = this.addRect.bind(this);
        this.addCircle = this.addCircle.bind(this);
        this.addTriangle = this.addTriangle.bind(this);
        this.downloadImg = this.downloadImg.bind(this);
        this.deleteElement = this.deleteElement.bind(this);
        this.setDrawingMode = this.setDrawingMode.bind(this);
        this.setLineWidth = this.setLineWidth.bind(this);
        this.loadImg = this.loadImg.bind(this);
        this.undo = this.undo.bind(this);
        this.redo = this.redo.bind(this);
    }

    componentDidMount() {
        this.startFabric();
    }

    componentDidUpdate() {

    }

    startFabric(){
        this.canvas = new fabric.Canvas('fabriccanvas');

        this.canvas.setHeight(500);
        this.canvas.setWidth(600);

        // Adding event listeners to the color inputs.

        let primaryColorInput = document.getElementById('primaryColor');
        let secondaryColorInput = document.getElementById('secondaryColor');

        if (primaryColorInput) {
            primaryColorInput.addEventListener('input', () => {
                this.primaryColor = primaryColorInput.value;
                this.canvas.freeDrawingBrush.color = this.primaryColor;
            });

            secondaryColorInput.addEventListener('input', () => {
                this.secondaryColor = secondaryColorInput.value;
            });
        }

        /*event handler for the file reader*/
        this.reader.onload = (event) => {
            let imgObj = new Image();
            imgObj.src = event.target.result;
            imgObj.onload = () => {
                let image = new fabric.Image(imgObj);
                image.set({
                    angle: 0,
                    padding: 0
                });
                this.canvas.centerObject(image);
                this.canvas.add(image);
                this.canvas.renderAll();
            };
        };

        /*
        // Event handlers for undo/redo
        this.canvas.on("object:added", (e) => {
            let object = e.target;
            //console.log('object:modified');

            if (this.canvasState.action === true) {
                this.canvasState.state = [this.canvasState.state[this.canvasState.index2]];
                this.canvasState.list = [this.canvasState.list[this.canvasState.index2]];
                this.canvasState.list = this.canvasState.list[];
                this.canvasState.action = false;
                this.canvasState.index = 1;
            }
            object.saveState();

            console.log(JSON.stringify(object.originalState));
            this.canvasState.state[this.canvasState.index] = object;
            this.canvasState.list[this.canvasState.index] = object;
            this.canvasState.index++;
            this.canvasState.index2 = this.canvasState.index - 1;
            this.canvasState.refresh = true;
        });

        this.canvas.on("object:modified", (e) => {
            let object = e.target;
            //console.log('object:modified');

            if (this.action === true) {
                this.canvasState.state = [this.canvasState.state[this.canvasState.index2]];
                this.canvasState.list = [this.canvasState.list[this.canvasState.index2]];

                this.canvasState.action = false;
                //console.log(state);
                this.canvasState.index = 1;
            }

            object.saveState();

            this.canvasState.state[this.canvasState.index] = object.originalState;
            this.list[this.canvasState.index] = object;
            this.canvasState.index++;
            this.canvasState.index2 = this.canvasState.index - 1;

            //console.log(state);
            this.canvasState.refresh = true;
        });*/

        // After each render save state of canvas

    }

    handleOpen(){
        $('#app').attr('aria-hidden', 'true');
        this.setState({
            modalOpen:true,
            activeTrap:true
        });

    }

    unmountTrap() {
        if(this.state.activeTrap){
            this.setState({ activeTrap: false });
            $('#app').attr('aria-hidden','false');
        }
    }

    addRect() {
        let coord = {left: 10, top: 10};
        this.canvas.add(new fabric.Rect({
            left: coord.left,
            top: coord.top,
            fill: this.primaryColor,
            width: 50,
            height: 50,
            opacity: 1
        }));
    }

    addCircle() {
        let coord = {left: 10, top: 10};

        this.canvas.add(new fabric.Circle({
            left: coord.left,
            top: coord.top,
            fill: this.primaryColor,
            radius: 50,
            opacity: 1
        }));
    }

    addTriangle() {
        let coord = {left: 10, top: 10};

        this.canvas.add(new fabric.Triangle({
            left: coord.left,
            top: coord.top,
            fill: this.primaryColor,
            width: 50,
            height: 50,
            opacity: 1
        }));
    }

    deleteElement() {
        let activeObjects = this.canvas.getActiveObjects();
        this.canvas.discardActiveObject();
        if (activeObjects.length) {
            this.canvas.remove.apply(this.canvas, activeObjects);
        }
    }

    setDrawingMode() {
        this.drawingMode = !this.drawingMode;
        this.canvas.isDrawingMode = this.drawingMode;
    }

    setLineWidth(event) {
        let value = parseInt(event.target.value, 10) || 1;
        this.canvas.freeDrawingBrush.width = value;
    }

    loadImg(event) {
        this.reader.readAsDataURL(event.target.files[0]);
    }

    downloadImg() {
        let href = this.canvas.toDataURL({
            format: 'png',
            quality: 1
        });

        let url = href.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');

        let a = document.createElement("a");
        a.style = "display: none";
        a.href = url;
        a.download = 'image.png';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }

    undo() {
        let objects = this.canvas.getObjects();
        if (objects.length !== 0) {
            let last = objects[objects.length - 1];
            this.objectsStack.push(last);
            this.canvas.remove(last);
            this.canvas.renderAll();
        }
        /*
        if (this.canvasState.index <= 0) {
            this.canvasState.index = 0;
            return;
        }

        if (this.canvasState.refresh === true) {
            this.canvasState.index--;
            this.canvasState.refresh = false;
        }

        this.canvasState.index2 = this.canvasState.index - 1;
        this.canvasState.current = this.canvasState.list[this.canvasState.index2];
        console.log(this.canvasState.current);
        console.log(this.canvasState.state);
        this.canvasState.current = this.canvasState.state[this.canvasState.index2];

        this.canvasState.index--;

        this.canvasState.current.setCoords();
        this.canvas.renderAll();
        this.canvasState.action = true;
*/
    }

    redo() {

        if (this.objectsStack.length > 0) {
            let object = this.objectsStack.pop();
            this.canvas.add(object);
        }

        /*
        this.canvasState.action = true;
        if (this.canvasState.index >= this.canvasState.state.length - 1) {
            return;
        }

        this.canvasState.index2 = this.canvasState.index + 1;
        this.canvasState.current = this.canvasState.list[this.canvasState.index2];
        this.canvasState.current.setOptions(JSON.parse(this.canvasState.state[this.canvasState.index2]));

        this.canvasState.index++;
        this.canvasState.current.setCoords();
        this.canvas.renderAll();
        */
    }

    render() {

        return(

            <Modal
                trigger={
                     this.handleKeyPress(evt, 'handleOpen')}>
                         Paint

                }
                open={this.state.modalOpen}
                onOpen={this.handleOpen}
                onClose={this.handleClose}
                id="paintModal"
                aria-labelledby="paintModalHeader"
                aria-describedby="paintModalDescription"
                tabIndex="0"
            >
                <FocusTrap
                    id="focus-trap-paintModal"
                    className = "header"
                    active={this.state.activeTrap}
                    focusTrapOptions={{
                        onDeactivate:this.unmountTrap,
                        clickOutsideDeactivates:true,
                        initialFocus: '#paintModalDescription'
                    }}
                >
                    <Modal.Header className="ui center aligned" id="paintModalHeader">

Draw and Paint

                    </Modal.Header>
                    <Modal.Content>
                        <Container>
                            <Segment color="blue" textAlign="left" padded>

Draw your own SVG image

                                <Segment textAlign="center" >

Draw inside the canvas using the tools provided.

                                    <button onClick={this.startFabric} onKeyPress={(evt) => this.handleKeyPress(evt, 'startFabric')}>Click and start drawing!</button>

                                    <canvas id="fabriccanvas" style={canvasStyle}/>

                                        <button onClick={this.addRect}>Add Rectangle</button>
                                        <button onClick={this.addCircle}>Add Circle</button>
                                        <button onClick={this.addTriangle}>Add Triangle</button>
                                        <button onClick={this.downloadImg}>Download Image</button>
                                        <input type="color" id="primaryColor"/>
                                        <input type="color" id="secondaryColor"/>
                                        <button onClick={this.deleteElement}>Delete selected objects</button>

                                            <input type="checkbox" name="newsletter" onClick={this.setDrawingMode}/>
                                            Drawing mode

                                        <input type="range" min="0" max="50" onChange={this.setLineWidth}/>

Load Image!
<input type="file" onChange={this.loadImg}/>

                                        <button onClick={this.undo}>Undo</button>
                                        <button onClick={this.redo}>Redo</button>

                                </Segment>
                            </Segment>

                        </Container>

                    </Modal.Content>

                </FocusTrap>
            </Modal>

        );
    }
}

PaintModal.contextTypes = {
    executeAction: React.PropTypes.func.isRequired,
    intl: React.PropTypes.object.isRequired
};

export default PaintModal;
<commit_msg>Added cancel button<commit_after>import React from 'react';
import FocusTrap from 'focus-trap-react';
import { Container, Modal, Segment } from 'semantic-ui-react';
let fileSaver = require('../../custom_modules/fabricjs/fileSaver');

const headerStyle = {
    'textAlign': 'center'
};

const canvasStyle = {
    'height': '0px',
    'width': '0px',
    'border': '1px solid #000000'
};

class PaintModal extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            modalOpen: false,
            activeTrap: false
        };

        //
        this.reader = new FileReader();
        this.primaryColor = 'black';
        this.secondaryColor = 'black';
        this.drawingMode = false;
        this.canvas = null;

        // For undo - redo
        /*this.canvasState = {
            current: null,
            list: [],
            state: [],
            index: 0,
            index2: 0,
            action: false,
            refresh: true,
        };
*/
        this.objectsStack = [];

        //
        this.handleOpen = this.handleOpen.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.unmountTrap = this.unmountTrap.bind(this);
        this.startFabric = this.startFabric.bind(this);
        this.addRect = this.addRect.bind(this);
        this.addCircle = this.addCircle.bind(this);
        this.addTriangle = this.addTriangle.bind(this);
        this.downloadImg = this.downloadImg.bind(this);
        this.deleteElement = this.deleteElement.bind(this);
        this.setDrawingMode = this.setDrawingMode.bind(this);
        this.setLineWidth = this.setLineWidth.bind(this);
        this.loadImg = this.loadImg.bind(this);
        this.undo = this.undo.bind(this);
        this.redo = this.redo.bind(this);
    }

    componentDidMount() {
        this.startFabric();
    }

    componentDidUpdate() {

    }

    startFabric(){
        this.canvas = new fabric.Canvas('fabriccanvas');

        this.canvas.setHeight(500);
        this.canvas.setWidth(600);

        // Adding event listeners to the color inputs.

        let primaryColorInput = document.getElementById('primaryColor');
        let secondaryColorInput = document.getElementById('secondaryColor');

        if (primaryColorInput) {
            primaryColorInput.addEventListener('input', () => {
                this.primaryColor = primaryColorInput.value;
                this.canvas.freeDrawingBrush.color = this.primaryColor;
            });

            secondaryColorInput.addEventListener('input', () => {
                this.secondaryColor = secondaryColorInput.value;
            });
        }

        /*event handler for the file reader*/
        this.reader.onload = (event) => {
            let imgObj = new Image();
            imgObj.src = event.target.result;
            imgObj.onload = () => {
                let image = new fabric.Image(imgObj);
                image.set({
                    angle: 0,
                    padding: 0
                });
                this.canvas.centerObject(image);
                this.canvas.add(image);
                this.canvas.renderAll();
            };
        };

        /*
        // Event handlers for undo/redo
        this.canvas.on("object:added", (e) => {
            let object = e.target;
            //console.log('object:modified');

            if (this.canvasState.action === true) {
                this.canvasState.state = [this.canvasState.state[this.canvasState.index2]];
                this.canvasState.list = [this.canvasState.list[this.canvasState.index2]];
                this.canvasState.list = this.canvasState.list[];
                this.canvasState.action = false;
                this.canvasState.index = 1;
            }
            object.saveState();

            console.log(JSON.stringify(object.originalState));
            this.canvasState.state[this.canvasState.index] = object;
            this.canvasState.list[this.canvasState.index] = object;
            this.canvasState.index++;
            this.canvasState.index2 = this.canvasState.index - 1;
            this.canvasState.refresh = true;
        });

        this.canvas.on("object:modified", (e) => {
            let object = e.target;
            //console.log('object:modified');

            if (this.action === true) {
                this.canvasState.state = [this.canvasState.state[this.canvasState.index2]];
                this.canvasState.list = [this.canvasState.list[this.canvasState.index2]];

                this.canvasState.action = false;
                //console.log(state);
                this.canvasState.index = 1;
            }

            object.saveState();

            this.canvasState.state[this.canvasState.index] = object.originalState;
            this.list[this.canvasState.index] = object;
            this.canvasState.index++;
            this.canvasState.index2 = this.canvasState.index - 1;

            //console.log(state);
            this.canvasState.refresh = true;
        });*/

        // After each render save state of canvas

    }

    handleOpen(){
        $('#app').attr('aria-hidden', 'true');
        this.setState({
            modalOpen:true,
            activeTrap:true
        });
    }

    handleClose(){
        $('#app').attr('aria-hidden', 'false');
        this.setState({
            modalOpen: false,
            activeTrap: false
        });
    }

    unmountTrap() {
        if(this.state.activeTrap){
            this.setState({ activeTrap: false });
            $('#app').attr('aria-hidden','false');
        }
    }

    addRect() {
        let coord = {left: 10, top: 10};
        this.canvas.add(new fabric.Rect({
            left: coord.left,
            top: coord.top,
            fill: this.primaryColor,
            width: 50,
            height: 50,
            opacity: 1
        }));
    }

    addCircle() {
        let coord = {left: 10, top: 10};

        this.canvas.add(new fabric.Circle({
            left: coord.left,
            top: coord.top,
            fill: this.primaryColor,
            radius: 50,
            opacity: 1
        }));
    }

    addTriangle() {
        let coord = {left: 10, top: 10};

        this.canvas.add(new fabric.Triangle({
            left: coord.left,
            top: coord.top,
            fill: this.primaryColor,
            width: 50,
            height: 50,
            opacity: 1
        }));
    }

    deleteElement() {
        let activeObjects = this.canvas.getActiveObjects();
        this.canvas.discardActiveObject();
        if (activeObjects.length) {
            this.canvas.remove.apply(this.canvas, activeObjects);
        }
    }

    setDrawingMode() {
        this.drawingMode = !this.drawingMode;
        this.canvas.isDrawingMode = this.drawingMode;
    }

    setLineWidth(event) {
        let value = parseInt(event.target.value, 10) || 1;
        this.canvas.freeDrawingBrush.width = value;
    }

    loadImg(event) {
        this.reader.readAsDataURL(event.target.files[0]);
    }

    downloadImg() {
        let href = this.canvas.toDataURL({
            format: 'png',
            quality: 1
        });

        let url = href.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');

        let a = document.createElement("a");
        a.style = "display: none";
        a.href = url;
        a.download = 'image.png';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }

    undo() {
        let objects = this.canvas.getObjects();
        if (objects.length !== 0) {
            let last = objects[objects.length - 1];
            this.objectsStack.push(last);
            this.canvas.remove(last);
            this.canvas.renderAll();
        }
        /*
        if (this.canvasState.index <= 0) {
            this.canvasState.index = 0;
            return;
        }

        if (this.canvasState.refresh === true) {
            this.canvasState.index--;
            this.canvasState.refresh = false;
        }

        this.canvasState.index2 = this.canvasState.index - 1;
        this.canvasState.current = this.canvasState.list[this.canvasState.index2];
        console.log(this.canvasState.current);
        console.log(this.canvasState.state);
        this.canvasState.current = this.canvasState.state[this.canvasState.index2];

        this.canvasState.index--;

        this.canvasState.current.setCoords();
        this.canvas.renderAll();
        this.canvasState.action = true;
*/
    }

    redo() {

        if (this.objectsStack.length > 0) {
            let object = this.objectsStack.pop();
            this.canvas.add(object);
        }

        /*
        this.canvasState.action = true;
        if (this.canvasState.index >= this.canvasState.state.length - 1) {
            return;
        }

        this.canvasState.index2 = this.canvasState.index + 1;
        this.canvasState.current = this.canvasState.list[this.canvasState.index2];
        this.canvasState.current.setOptions(JSON.parse(this.canvasState.state[this.canvasState.index2]));

        this.canvasState.index++;
        this.canvasState.current.setCoords();
        this.canvas.renderAll();
        */
    }

    render() {

        return(

            <Modal
                trigger={
                     this.handleKeyPress(evt, 'handleOpen')}>
                         Paint

                }
                open={this.state.modalOpen}
                onOpen={this.handleOpen}
                onClose={this.handleClose}
                id="paintModal"
                aria-labelledby="paintModalHeader"
                aria-describedby="paintModalDescription"
                tabIndex="0"
            >
                <FocusTrap
                    id="focus-trap-paintModal"
                    className = "header"
                    active={this.state.activeTrap}
                    focusTrapOptions={{
                        onDeactivate:this.unmountTrap,
                        clickOutsideDeactivates:true,
                        initialFocus: '#paintModalDescription'
                    }}
                >
                    <Modal.Header className="ui center aligned" id="paintModalHeader">

Draw and Paint

                    </Modal.Header>
                    <Modal.Content>
                        <Container>
                            <Segment color="blue" textAlign="left" padded>

Draw your own SVG image

                                <Segment textAlign="center" >

Draw inside the canvas using the tools provided.

                                    <button onClick={this.startFabric} onKeyPress={(evt) => this.handleKeyPress(evt, 'startFabric')}>Click and start drawing!</button>

                                    <canvas id="fabriccanvas" style={canvasStyle}/>

                                        <button onClick={this.addRect}>Add Rectangle</button>
                                        <button onClick={this.addCircle}>Add Circle</button>
                                        <button onClick={this.addTriangle}>Add Triangle</button>
                                        <button onClick={this.downloadImg}>Download Image</button>
                                        <input type="color" id="primaryColor"/>
                                        <input type="color" id="secondaryColor"/>
                                        <button onClick={this.deleteElement}>Delete selected objects</button>

                                            <input type="checkbox" name="newsletter" onClick={this.setDrawingMode}/>
                                            Drawing mode

                                        <input type="range" min="0" max="50" onChange={this.setLineWidth}/>

Load Image!
<input type="file" onChange={this.loadImg}/>

                                        <button onClick={this.undo}>Undo</button>
                                        <button onClick={this.redo}>Redo</button>

                                </Segment>
                            </Segment>

                        </Container>

                            <button type="cancel" onClick={this.handleClose} className="ui cancel button">

                                Cancel
                            </button>

                    </Modal.Content>

                </FocusTrap>
            </Modal>

        );
    }
}

PaintModal.contextTypes = {
    executeAction: React.PropTypes.func.isRequired,
    intl: React.PropTypes.object.isRequired
};

export default PaintModal;
<|endoftext|>