'use strict';

var should = require('should'),
  request = require('supertest'),
  path = require('path'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  Attestation = mongoose.model('Attestation'),
  express = require(path.resolve('./config/lib/express'));

/**
 * Globals
 */
var app, agent, credentials, user, attestation;

/**
 * Attestation routes tests
 */
describe('Attestation CRUD tests', function () {

  before(function (done) {
    // Get application
    app = express.init(mongoose);
    agent = request.agent(app);

    done();
  });

  beforeEach(function (done) {
    // Create user credentials
    credentials = {
      username: 'username',
      password: 'M3@n.jsI$Aw3$0m3'
    };

    // Create a new user
    user = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'test@test.com',
      username: credentials.username,
      password: credentials.password,
      provider: 'local'
    });

    // Save a user to the test db and create new attestation
    user.save(function () {
      attestation = {
        title: 'Attestation Title',
        content: 'Attestation Content'
      };

      done();
    });
  });

  it('should be able to save an attestation if logged in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new attestation
        agent.post('/api/attestations')
          .send(attestation)
          .expect(200)
          .end(function (attestationSaveErr, attestationSaveRes) {
            // Handle attestation save error
            if (attestationSaveErr) {
              return done(attestationSaveErr);
            }

            // Get a list of attestations
            agent.get('/api/attestations')
              .end(function (attestationsGetErr, attestationsGetRes) {
                // Handle attestation save error
                if (attestationsGetErr) {
                  return done(attestationsGetErr);
                }

                // Get attestations list
                var attestations = attestationsGetRes.body;

                // Set assertions
                (attestations[0].user._id).should.equal(userId);
                (attestations[0].title).should.match('Attestation Title');

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should not be able to save an attestation if not logged in', function (done) {
    agent.post('/api/attestations')
      .send(attestation)
      .expect(403)
      .end(function (attestationSaveErr, attestationSaveRes) {
        // Call the assertion callback
        done(attestationSaveErr);
      });
  });

  it('should not be able to save an attestation if no title is provided', function (done) {
    // Invalidate title field
    attestation.title = '';

    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new attestation
        agent.post('/api/attestations')
          .send(attestation)
          .expect(400)
          .end(function (attestationSaveErr, attestationSaveRes) {
            // Set message assertion
            (attestationSaveRes.body.message).should.match('Title cannot be blank');

            // Handle attestation save error
            done(attestationSaveErr);
          });
      });
  });

  it('should be able to update an attestation if signed in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new attestation
        agent.post('/api/attestations')
          .send(attestation)
          .expect(200)
          .end(function (attestationSaveErr, attestationSaveRes) {
            // Handle attestation save error
            if (attestationSaveErr) {
              return done(attestationSaveErr);
            }

            // Update attestation title
            attestation.title = 'WHY YOU GOTTA BE SO MEAN?';

            // Update an existing attestation
            agent.put('/api/attestations/' + attestationSaveRes.body._id)
              .send(attestation)
              .expect(200)
              .end(function (attestationUpdateErr, attestationUpdateRes) {
                // Handle attestation update error
                if (attestationUpdateErr) {
                  return done(attestationUpdateErr);
                }

                // Set assertions
                (attestationUpdateRes.body._id).should.equal(attestationSaveRes.body._id);
                (attestationUpdateRes.body.title).should.match('WHY YOU GOTTA BE SO MEAN?');

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should be able to get a list of attestations if not signed in', function (done) {
    // Create new attestation model instance
    var attestationObj = new Attestation(attestation);

    // Save the attestation
    attestationObj.save(function () {
      // Request attestations
      request(app).get('/api/attestations')
        .end(function (req, res) {
          // Set assertion
          res.body.should.be.instanceof(Array).and.have.lengthOf(1);

          // Call the assertion callback
          done();
        });

    });
  });

  it('should be able to get a single attestation if not signed in', function (done) {
    // Create new attestation model instance
    var attestationObj = new Attestation(attestation);

    // Save the attestation
    attestationObj.save(function () {
      request(app).get('/api/attestations/' + attestationObj._id)
        .end(function (req, res) {
          // Set assertion
          res.body.should.be.instanceof(Object).and.have.property('title', attestation.title);

          // Call the assertion callback
          done();
        });
    });
  });

  it('should return proper error for single attestation with an invalid Id, if not signed in', function (done) {
    // test is not a valid mongoose Id
    request(app).get('/api/attestations/test')
      .end(function (req, res) {
        // Set assertion
        res.body.should.be.instanceof(Object).and.have.property('message', 'Attestation is invalid');

        // Call the assertion callback
        done();
      });
  });

  it('should return proper error for single attestation which doesnt exist, if not signed in', function (done) {
    // This is a valid mongoose Id but a non-existent attestation
    request(app).get('/api/attestations/559e9cd815f80b4c256a8f41')
      .end(function (req, res) {
        // Set assertion
        res.body.should.be.instanceof(Object).and.have.property('message', 'No attestation with that identifier has been found');

        // Call the assertion callback
        done();
      });
  });

  it('should be able to delete an attestation if signed in', function (done) {
    agent.post('/api/auth/signin')
      .send(credentials)
      .expect(200)
      .end(function (signinErr, signinRes) {
        // Handle signin error
        if (signinErr) {
          return done(signinErr);
        }

        // Get the userId
        var userId = user.id;

        // Save a new attestation
        agent.post('/api/attestations')
          .send(attestation)
          .expect(200)
          .end(function (attestationSaveErr, attestationSaveRes) {
            // Handle attestation save error
            if (attestationSaveErr) {
              return done(attestationSaveErr);
            }

            // Delete an existing attestation
            agent.delete('/api/attestations/' + attestationSaveRes.body._id)
              .send(attestation)
              .expect(200)
              .end(function (attestationDeleteErr, attestationDeleteRes) {
                // Handle attestation error error
                if (attestationDeleteErr) {
                  return done(attestationDeleteErr);
                }

                // Set assertions
                (attestationDeleteRes.body._id).should.equal(attestationSaveRes.body._id);

                // Call the assertion callback
                done();
              });
          });
      });
  });

  it('should not be able to delete an attestation if not signed in', function (done) {
    // Set attestation user
    attestation.user = user;

    // Create new attestation model instance
    var attestationObj = new Attestation(attestation);

    // Save the attestation
    attestationObj.save(function () {
      // Try deleting attestation
      request(app).delete('/api/attestations/' + attestationObj._id)
        .expect(403)
        .end(function (attestationDeleteErr, attestationDeleteRes) {
          // Set message assertion
          (attestationDeleteRes.body.message).should.match('User is not authorized');

          // Handle attestation error error
          done(attestationDeleteErr);
        });

    });
  });

  afterEach(function (done) {
    User.remove().exec(function () {
      Attestation.remove().exec(done);
    });
  });
});
