var qs = require('querystring')
var response = require('response');
var JSONStream = require('JSONStream');
var jsonBody = require('body/json');
var Router = require('match-routes');
var CSV = require('comma-separated-values');

module.exports = function (server, prefix) {
  var prefix = prefix || '/api/v2/';
  var permissions = require('../lib/permissions')(server);
  var router = Router();
  
  router.on(prefix + 'sheets', function (req, res, opts) {

    /*
     *  Get list of sheets
     */

    if (req.method === 'GET') {
      var query = qs.parse(opts.parsedUrl.query)
      res.setHeader('Content-Type', 'application/json');
      permissions.authorize(req, function (err, account) {
        if (err || !account) {
          return server.sheets.list({ filter: { private: false }})
            .pipe(JSONStream.stringify())
            .pipe(res);
        }

        if (account.admin) {
          return server.sheets.list()
            .pipe(JSONStream.stringify())
            .pipe(res);
        }

        return server.sheets.list({ filter: { accessible: account.username }})
          .pipe(JSONStream.stringify())
          .pipe(res);
      })
    }

    /*
     *  Create new sheet
     */

    if (req.method === 'POST') {
      permissions.authorize(req, res, function (err, account) {
        if (err) response().json({ error: 'Unauthorized'}).status(401).pipe(res);

        jsonBody(req, res, function (err, body) {
          server.sheets.create(body, function (err, sheet) {
            if (err || !sheet) {
              var data = { message: 'Not found', statusCode: 404 };
              return response.json(data).status(404).pipe(res);
            }

            else return response.json(sheet).pipe(res);
          });
        });
      });
    }

  });



  router.on(prefix + 'sheets/:key', function (req, res, opts) {

    /*
     *  Get individual sheet
     */

    if (req.method === 'GET') {
      permissions.authorize(req, res, function (err, account) {
        server.sheets.get(opts.params.key, function (err, sheet) {          

          if (permissions.sheetAccessible(sheet, account)) {
            return response.json(sheet).pipe(res);
          }

          return response.json({ message: 'Not found', statusCode: 404 }).status(404).pipe(res);
        });
      });
    }


    /*
     *  Update sheet
     */

    if (req.method === 'PUT') {
      permissions.authorize(req, res, function (err, account) {
        if (err) response().json({ error: 'Unauthorized'}).status(401).pipe(res);

        jsonBody(req, res, function (err, body) {
          server.sheets.update(opts.params.key, body, function (err, sheet) {
            if (err || !sheet) {
              var data = { message: 'Not found', statusCode: 404 };
              return response.json(data).status(404).pipe(res);
            }

            else return response.json(sheet).pipe(res);
          });
        });
      });
    }



    /*
     *  Destroy sheet
     */

    if (req.method === 'DELETE') {
      permissions.authorize(req, res, function (err, account) {
        if (err) response().json({ error: 'Unauthorized'}).status(401).pipe(res);

        server.sheets.destroy(opts.params.key, function (err) {
          if (err) {
            var data = { message: 'Server error', statusCode: 500 };
            return response.json(data).status(500).pipe(res);
          }

          res.writeHead(204);
          return res.end();
        });
      });
    }
  });

  router.on(prefix + 'sheets/:key/csv', function (req, res, opts) {
    permissions.authorize(req, res, function (err, account) {
      server.sheets.get(opts.params.key, function (err, sheet) {
        
        if (permissions.sheetAccessible(sheet, account)) {
          var csv = new CSV(sheet.rows, {header:true}).encode()
          return response().txt(csv).pipe(res)
        }

        return response.json({ message: 'Not found', statusCode: 404 }).status(404).pipe(res);
      });
    });
  });

  return router;
};

/*
 * Helper functions
 */

function filterSheetDetails () {
  return through.obj(function iterator(chunk, enc, next) {
    this.push(filter(chunk, ['*', '!editors', '!owners']));
    next();
  });
}
@@ -1939,38 +1939,41 @@
     
-permissions.authorize(req, res
+server.sheets.get(opts.params.key
 , fu
@@ -1977,38 +1977,36 @@
  function (err, 
-accoun
+shee
 t) %7B%0A        ser
@@ -2006,77 +2006,142 @@
     
-server.sheets.get(opts.params.key, function (err, sheet) %7B          %0A
+if (sheet && !sheet.private) return response.json(sheet).pipe(res);%0A%0A        permissions.authorize(req, res, function (err, account) %7B
 %0A   

fix public sheet api endpoint