"use strict";

var ObjectId = require('bson').ObjectID;
var Document = require('./document');
var TemplateReference = require('./template-reference');
var DOCUMENT_STATUS = require('../../constant/procedure/document-status.constant');
describe('Document', function () {
  it('should populate document id as ObjectId if id exists', function () {
    var document = new Document({
      _id: '5808fa7fae73b626daa89192'
    });
    expect(document._id instanceof ObjectId).toBeTruthy();
  });
  it('should validate a document', function () {
    var user = {
      firstName: 'Semar',
      lastName: 'Prom',
      campusCode: '01',
      tenantCode: 'UC',
      userId: 'VUN8MDF8cy5wcm9tQGJlcmtlbGV5LmVkdQ'
    };
    var document = new Document({
      _id: '599d0dd68991560000077a9c',
      template: {
        _id: '580fc49c5e649fbd9218d3f3',
        types: ['LOTO'],
        campusCode: ['ALL'],
        tenantCode: ['ALL'],
        name: 'Basic LOTO Procedure'
      },
      title: 'SawStop Table Saw',
      description: 'Industrial SawStop table saw.',
      status: 'DRAFT',
      createdBy: user,
      createdDate: '2017-08-23T05:08:38.714Z',
      expirationDate: null,
      lastModifiedBy: user,
      lastModifiedDate: '2017-08-23T05:08:38.714Z',
      access: [],
      label: {
        a: 0,
        b: 'string',
        c: false
      }
    });
    var validation = document.validate();
    expect(validation.valid).toEqual(true);
  });
  it('should set expirationDate ', function () {
    var document = new Document();
    var duration = 1;
    var expected = new Date();
    expected.setDate(expected.getDate() + duration);
    document.setExpirationDate(duration);
    expect(document.expirationDate.getDate()).toEqual(expected.getDate());
  });
  it('should clone a document and remove attachments', function () {
    var document = new Document({
      _id: '5808fa7fae73b626daa89192',
      template: {
        _id: '5808fa7fae73b626daa89192',
        types: ['LOTO'],
        maxExpirationDays: null,
        tenantCode: ['ALL'],
        campusCode: ['ALL']
      },
      title: 'Title',
      description: 'this is a description',
      access: [],
      sections: [{
        id: '58346a1e44187c3dff1570b9',
        allowableCards: [{
          allowAttachments: false,
          type: 'TEXT'
        }],
        cards: [{
          id: '5834619518d49e2c51725e0d',
          type: 'TEXT',
          isRequired: false,
          allowAttachments: true,
          attachments: ['picture', 'another picture'],
          details: {
            text: 'some text'
          }
        }]
      }],
      createdBy: {
        firstName: 'Ian'
      },
      createdDate: new Date('2016-11-5T15:42:35.620Z'),
      lastModifiedBy: {
        firstName: 'Ian'
      },
      lastModifiedDate: new Date('2016-11-22T15:42:35.620Z')
    });
    var newTitle = 'New Title';
    var clonedDocument = Document.clone(document, {
      title: newTitle,
      description: 'some updated description'
    });
    expect(clonedDocument._id.toString()).not.toEqual('5808fa7fae73b626daa89192');
    expect(clonedDocument.sections[0].id.toString()).not.toEqual('5808fa7fae73b626daa89192');
    expect(clonedDocument.sections[0].cards[0].id.toString()).not.toEqual('5834619518d49e2c51725e0d');
    expect(clonedDocument.createdBy).toBeNull();
    expect(clonedDocument.lastModifiedBy).toBeNull();
    expect(clonedDocument.template).toEqual(document.template);
    expect(clonedDocument.title).toEqual(newTitle);
  });
  it('should clone a document with an acknowledgement card and remove signatures', function () {
    var document = new Document({
      _id: '5b32afb68ec988000028ee4d',
      template: {
        _id: '5b084c570422b90000b89a2c',
        types: ['MEDICAL'],
        maxExpirationDays: null,
        tenantCode: ['ALL'],
        campusCode: ['ALL']
      },
      title: 'Title',
      description: 'this is a description',
      access: [],
      sections: [{
        id: '5acbe189bfb158000036760a',
        allowableCards: [],
        cards: [{
          id: '5834619518d49e2c51725e0d',
          type: 'ACKNOWLEDGEMENT',
          isRequired: true,
          allowAttachments: false,
          attachments: [],
          details: {
            acknowledgeLabel: 'Acknowledged by: ',
            prompt: 'I have read and acknowledge the contents, requirements, and responsibilities outlined in this procedure.',
            signatures: [{
              date: '2018-08-30T17:09:51.408Z',
              person: {
                userId: 'VUN8MDN8dGFqaGFAdWNkYXZpcy5lZHU',
                firstName: 'Trevor',
                lastName: 'Jha'
              }
            }]
          }
        }]
      }],
      createdBy: {
        firstName: 'Ian'
      },
      createdDate: new Date('2016-11-5T15:42:35.620Z'),
      lastModifiedBy: {
        firstName: 'Ian'
      },
      lastModifiedDate: new Date('2016-11-22T15:42:35.620Z')
    });
    var newTitle = 'New Title';
    var clonedDocument = Document.clone(document, {
      title: newTitle,
      description: 'some updated description'
    });
    expect(clonedDocument._id.toString()).not.toEqual('5b32afb68ec988000028ee4d');
    expect(clonedDocument.sections[0].id.toString()).not.toEqual('5acbe189bfb158000036760a');
    expect(clonedDocument.sections[0].cards[0].id.toString()).not.toEqual('5834619518d49e2c51725e0d');
    expect(clonedDocument.sections[0].cards[0].details.signatures).toHaveLength(0);
    expect(clonedDocument.createdBy).toBeNull();
    expect(clonedDocument.lastModifiedBy).toBeNull();
    expect(clonedDocument.template).toEqual(document.template);
    expect(clonedDocument.title).toEqual(newTitle);
  });
  it('should create a new document from a template', function () {
    var template = {
      _id: new ObjectId('58864f51ba32a020a8b377a6'),
      name: 'TEMPLATE',
      types: ['TEST'],
      sectionDefinitions: [{
        header: 'SECTION 1',
        allowableCards: [{
          type: 'TEXT',
          allowAttachments: true
        }],
        cardDefinitions: [{
          type: 'CHECKBOX',
          id: new ObjectId('5807aaf31c06040000dccf28'),
          isRequired: true,
          isMovable: false,
          isEditable: false,
          allowAttachments: false,
          details: {
            name: 'checkbox card',
            optionsId: new ObjectId('5807aaf31c06040000dccf28'),
            selectedOptions: [],
            notes: null
          }
        }]
      }]
    };
    var doc = Document.fromTemplate(template, {
      title: 'TITLE',
      createdBy: {
        firstName: 'Ian',
        lastName: 'Holser',
        userId: 'VUN8MDN8aWZoQHVjZGF2aXMuZWR1',
        tenantCode: 'UC',
        campusCode: '03'
      }
    });
    delete doc._id;
    doc.sections = doc.sections.map(function (section) {
      section.cards.map(function (card) {
        delete card.id; //eslint-disable-line
        return card;
      });
      delete section.id; // eslint-disable-line
      return section;
    });
    var newDocument = new Document({
      title: 'TITLE',
      status: 'DRAFT',
      createdBy: {
        firstName: 'Ian',
        lastName: 'Holser',
        userId: 'VUN8MDN8aWZoQHVjZGF2aXMuZWR1',
        tenantCode: 'UC',
        campusCode: '03'
      },
      access: [],
      createdDate: null,
      description: null,
      expirationDate: null,
      group: null,
      lastModifiedBy: null,
      lastModifiedDate: null,
      readyForUseBy: null,
      readyForUseDate: null,
      template: new TemplateReference(template),
      sections: [{
        allowableCards: [{
          type: 'TEXT',
          allowAttachments: true
        }],
        header: 'SECTION 1',
        cards: [{
          type: 'CHECKBOX',
          allowAttachments: false,
          attachments: [],
          id: new ObjectId('5807aaf31c06040000dccf28'),
          isEditable: false,
          isMovable: false,
          isRequired: true,
          details: {
            name: 'checkbox card',
            countLabel: null,
            count: null,
            optionsId: new ObjectId('5807aaf31c06040000dccf28'),
            selectedOptions: [],
            notes: null
          }
        }]
      }]
    });
    delete newDocument._id;
    delete newDocument.sections[0].id;
    delete newDocument.sections[0].cards[0].id;
    expect(doc).toEqual(newDocument);
  });
  it('should create a document from a template marked create by system', function () {
    var template = {
      _id: new ObjectId('507f191e810c19729de860ea'),
      name: 'Created by the system',
      campusCode: ['ALL'],
      tenantCode: ['ALL'],
      status: 'PUBLISHED',
      maxExpirationDays: 365,
      // days
      types: ['LOTO'],
      preventClone: false,
      preventRemove: false,
      createBySystem: true,
      sectionDefinitions: []
    };
    var doc = Document.fromTemplate(template, {
      title: 'I am created by the system'
    });
    expect(doc.status).toEqual(DOCUMENT_STATUS.READY_FOR_USE_BY_SYSTEM);
  });
  it('should calculate counts for a document', function () {
    var doc = new Document({
      title: 'TITLE',
      sections: [{
        cards: [{
          type: 'CHECKBOX',
          details: {
            name: 'checkbox card',
            countLabel: 'Locks/Tags',
            count: 3,
            selectedOptions: [{
              count: 1
            }, {
              count: 2
            }]
          }
        }, {
          type: 'CHECKBOX',
          details: {
            name: 'card',
            countLabel: 'Assets',
            count: 1,
            selectedOptions: [{
              count: 1
            }]
          }
        }, {
          type: 'CHECKBOX',
          details: {
            name: 'name',
            countLabel: 'Assets',
            count: null,
            selectedOptions: []
          }
        }, {
          type: 'CHECKBOX',
          details: {
            name: 'name',
            countLabel: null,
            count: null,
            selectedOptions: []
          }
        }]
      }, {
        cards: [{
          type: 'CONDITION',
          details: {
            cards: [{
              type: 'CHECKBOX',
              details: {
                name: 's',
                countLabel: 'Locks/Tags',
                count: null,
                selectedOptions: [{
                  count: 1
                }]
              }
            }]
          }
        }]
      }]
    });
    expect(doc.calculateCounts()).toEqual({
      labels: ['Locks/Tags', 'Assets'],
      counts: [4, 1]
    });
  });
  it('should clone a document and add allowComment', function () {
    var document = new Document({
      _id: '5808fa7fae73b626daa89492',
      template: {
        _id: '5ba138e9b9c140b9844abe64',
        types: ['AGENDA'],
        maxExpirationDays: 365,
        tenantCode: ['UC'],
        campusCode: ['03']
      },
      title: 'Title',
      description: 'this is a description',
      access: [],
      sections: [{
        id: '5c0ef394a31255000085e861',
        allowableCards: [{
          allowAttachments: false,
          type: 'BUA'
        }],
        cards: [{
          id: '5c0ef394a31255000085e86a',
          type: 'BUA',
          attachments: [],
          comment: '',
          isRequired: false,
          isMovable: false,
          isEditable: true,
          allowAttachments: false,
          allowComment: false,
          details: {
            buaId: null
          }
        }]
      }],
      createdBy: {
        firstName: 'Saurit'
      },
      createdDate: new Date('2018-12-10T23:15:32.289Z'),
      lastModifiedBy: {
        firstName: 'Saurit'
      },
      lastModifiedDate: new Date('2018-12-10T23:15:32.289Z')
    });
    var clonedDocument = Document.cloneWithCommentsAllowed(document, {
      title: document.title,
      description: document.title
    });
    expect(clonedDocument._id.toString()).not.toEqual('5808fa7fae73b626daa89492');
    expect(clonedDocument.sections[0].id.toString()).not.toEqual('5c0ef394a31255000085e861');
    expect(clonedDocument.sections[0].cards[0].id.toString()).not.toEqual('5c0ef394a31255000085e86a');
    expect(clonedDocument.createdBy).toBeNull();
    expect(clonedDocument.lastModifiedBy).toBeNull();
    expect(clonedDocument.template).toEqual(document.template);
    expect(clonedDocument.title).toEqual(document.title);
  });
  it.only('should contruct a label from a chemical band card', function () {
    var document = new Document({
      _id: new ObjectId('5c75c231488eb600005c45f7'),
      template: {
        _id: new ObjectId('5c65e2716b23d100009b0dbf'),
        name: 'Chemical Band SOP',
        types: ['SOP'],
        tenantCode: ['UC'],
        campusCode: ['03'],
        preventClone: false,
        preventRemove: false,
        preventShare: false,
        preventEditTitle: false,
        maxExpirationDays: null
      },
      title: 'carbon rod',
      description: null,
      sections: [{
        id: new ObjectId('5c75c231488eb600005c45f3'),
        header: null,
        allowableCards: ['CHEMICAL_BAND'],
        cards: [{
          id: new ObjectId('5c75c231488eb600005c45f4'),
          type: 'CHEMICAL_BAND',
          attachments: [],
          comment: null,
          isRequired: false,
          isMovable: false,
          isEditable: true,
          allowAttachments: true,
          allowComment: false,
          details: {
            notes: null,
            bands: [{
              _id: new ObjectId('5aa6d9bbf7fbe1b44eedc7f1'),
              name: 'Cryogenic Inert',
              suffix: null,
              family: null,
              cas: [],
              ghs: [],
              excludes: null,
              tenant: null,
              campus: null
            }]
          }
        }]
      }],
      status: 'DRAFT',
      access: [{
        id: 'VUN8MDN8a2NoaW5lbkB1Y2RhdmlzLmVkdQ',
        displayName: 'Kumi Chinen',
        tenantCode: 'UC',
        campusCode: '03',
        permission: 'OWNER',
        type: 'PERSON'
      }],
      createdBy: {
        userId: 'VUN8MDN8a2NoaW5lbkB1Y2RhdmlzLmVkdQ',
        firstName: 'Kumi',
        lastName: 'Chinen',
        tenantCode: 'UC',
        campusCode: '03'
      },
      createdDate: new Date('2019-02-26T22:48:17.132+0000'),
      lastModifiedBy: {
        userId: 'VUN8MDN8a2NoaW5lbkB1Y2RhdmlzLmVkdQ',
        firstName: 'Kumi',
        lastName: 'Chinen',
        tenantCode: 'UC',
        campusCode: '03'
      },
      lastModifiedDate: new Date('2019-02-26T22:48:49.345+0000'),
      expirationDate: null,
      readyForUseDate: null,
      readyForUseBy: null,
      label: {
        inventoryId: '5b05eb8e3c4e3525d375be97'
      }
    });
    expect(document.label["band:".concat(document.sections[0].cards[0].details.bands[0]._id)]).not.toBeNull();
  });
});