'use strict';

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

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

/**
 * attestment routes tests
 */
describe('attestment 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 attestment
    user.save(function () {
      attestment = {
        title: 'attestment Title',
        content: 'attestment Content'
      };

      done();
    });
  });

  it('should be able to save an attestment 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 attestment
        agent.post('/api/attestments')
          .send(attestment)
          .expect(200)
          .end(function (attestmentSaveErr, attestmentSaveRes) {
            // Handle attestment save error
            if (attestmentSaveErr) {
              return done(attestmentSaveErr);
            }

            // Get a list of attestments
            agent.get('/api/attestments')
              .end(function (attestmentsGetErr, attestmentsGetRes) {
                // Handle attestment save error
                if (attestmentsGetErr) {
                  return done(attestmentsGetErr);
                }

                // Get attestments list
                var attestments = attestmentsGetRes.body;

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

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

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

  it('should not be able to save an attestment if no title is provided', function (done) {
    // Invalidate title field
    attestment.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 attestment
        agent.post('/api/attestments')
          .send(attestment)
          .expect(400)
          .end(function (attestmentSaveErr, attestmentSaveRes) {
            // Set message assertion
            (attestmentSaveRes.body.message).should.match('Title cannot be blank');

            // Handle attestment save error
            done(attestmentSaveErr);
          });
      });
  });

  it('should be able to update an attestment 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 attestment
        agent.post('/api/attestments')
          .send(attestment)
          .expect(200)
          .end(function (attestmentSaveErr, attestmentSaveRes) {
            // Handle attestment save error
            if (attestmentSaveErr) {
              return done(attestmentSaveErr);
            }

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

            // Update an existing attestment
            agent.put('/api/attestments/' + attestmentSaveRes.body._id)
              .send(attestment)
              .expect(200)
              .end(function (attestmentUpdateErr, attestmentUpdateRes) {
                // Handle attestment update error
                if (attestmentUpdateErr) {
                  return done(attestmentUpdateErr);
                }

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

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

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

    // Save the attestment
    attestmentObj.save(function () {
      // Request attestments
      request(app).get('/api/attestments')
        .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 attestment if not signed in', function (done) {
    // Create new attestment model instance
    var attestmentObj = new attestment(attestment);

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

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

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

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

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

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

  it('should be able to delete an attestment 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 attestment
        agent.post('/api/attestments')
          .send(attestment)
          .expect(200)
          .end(function (attestmentSaveErr, attestmentSaveRes) {
            // Handle attestment save error
            if (attestmentSaveErr) {
              return done(attestmentSaveErr);
            }

            // Delete an existing attestment
            agent.delete('/api/attestments/' + attestmentSaveRes.body._id)
              .send(attestment)
              .expect(200)
              .end(function (attestmentDeleteErr, attestmentDeleteRes) {
                // Handle attestment error error
                if (attestmentDeleteErr) {
                  return done(attestmentDeleteErr);
                }

                // Set assertions
                (attestmentDeleteRes.body._id).should.equal(attestmentSaveRes.body._id);

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

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

    // Create new attestment model instance
    var attestmentObj = new attestment(attestment);

    // Save the attestment
    attestmentObj.save(function () {
      // Try deleting attestment
      request(app).delete('/api/attestments/' + attestmentObj._id)
        .expect(403)
        .end(function (attestmentDeleteErr, attestmentDeleteRes) {
          // Set message assertion
          (attestmentDeleteRes.body.message).should.match('User is not authorized');

          // Handle attestment error error
          done(attestmentDeleteErr);
        });

    });
  });

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