var express = require('express');
var createError = require('http-errors')
var router = express.Router();

const models = require('../../../models');
const utils = require('../../../libs/utils');

const auth = require('../../../libs/auth');


let artUserPopulates = Object.keys(models.Art.schema.paths)
  .filter(path => 'User' == models.Art.schema.path(path).options.ref)
  .map(path => ({ path, select: 'username name' }));
console.log('artUserPopulates:', artUserPopulates);


/**表头 */
router.get('/pager/headers', auth.need('read:own', 'art'), utils.pager.getHeadersBuilder(models.Art));

/**所有作品列表  */
router.get('/pager/all', auth.need('read:any', 'art'), (req, res, next) => {
  (async () => {
    req.query.base = { drop: false };
    next();
  })().catch(next)
}, utils.pager.getListBuilder(models.Art, artUserPopulates));

/**回收站列表 */
router.get('/pager/removed', auth.need('read:own', 'art'),
  (req, res, next) => {
    (async () => {
      req.query.base = { drop: true }
      let ac = await auth.getAc(req);
      if (!ac.can('user').readAny('art').granted) {
        req.query.base.user = req.session.user._id;
      }
      next();
    })().catch(next)
  }, utils.pager.getListBuilder(models.Art, artUserPopulates));


/**我的作品列表 */
router.get('/pager/my', auth.need('read:own', 'art'), (req, res, next) => {
  (async () => {
    req.query.base = {
      user: req.session.user._id,
      drop: false,
    }
    next();
  })().catch(next)
}, utils.pager.getListBuilder(models.Art, artUserPopulates));


/**获取某个用户的作品列表 */
router.get('/pager/user/:username', auth.need('read:any', 'art'), (req, res, next) => {
  (async () => {
    let { username } = req.params;
    let user = await models.User.findOne({ username });
    if (!user) throw createError(404, '用户不存在');
    req.query.base = {
      user: user._id,
      drop: false,
    }
    next();
  })().catch(next)
}, utils.pager.getListBuilder(models.Art, artUserPopulates));


/**待发布列表*/
router.get('/pager/pending', auth.need('read:any', 'art-publish'), (req, res, next) => {
  (async () => {
    req.query.base = {
      drop: false,
      status: 7000,
      $or: [{ publishSchedule: { $exists: false } }, { publishSchedule: null }]
    }
    next();
  })().catch(next)
}, utils.pager.getListBuilder(models.Art, artUserPopulates));





/**
 *
 * 获取作品基础信息, 排除任何二进制数据
 *
 */
router.get('/:id', auth.need('read:own', 'art'), function (req, res, next) {
  (async function () {

    let user = req.session.user._id;
    let id = req.params.id;
    utils.validators.validateId(id);
    /**@type {Query} */
    let query = models.Art.findOne({ $or: [{ _id: id }, { pageId: id }] });
    // query.populate({ path: 'bins', select: '-data' });
    artUserPopulates.forEach(p => {
      query.populate(p);
    })
    query.populate({ path: 'publishSchedule', select: 'done' });

    let doc = await query.exec();
    if (!doc) throw createError(404, '作品不存在!')

    let ac = await auth.getAc(req);
    if (!ac.can('user').readAny('art').granted && doc.user._id != req.session.user._id) {
      throw createError(403, '权限不足');
    }

    let out = doc.toObject();

    if (doc.work) { out.zip = utils.thumb.zipPath(doc._id); }

    if (out.upstream) {
      let { upstreamBase } = req.app.get('app-config');
      out.upstreamUrl = `${upstreamBase}/app/pages/detail/${doc._id}`;
    }

    res.json(out);
  })().catch(next)
});


/**
 * 更新作品tags,name
 * patch-meta
 */
router.patch('/meta', auth.need('update:own', 'art'), (req, res, next) => {
  (async function () {
    let user = req.session.user._id;
    let { tags, name, desc, epgs, pageId, } = req.body;
    if (!tags || !name || !epgs || !Array.isArray(tags)) {
      throw createError(400, '参数错误');
    }
    tags = tags.map(t => t.trim()).filter(t => t);
    utils.validators.validateId(pageId, 'ID错误');

    let doc = await models.Art.findById(pageId);
    if (!doc) throw createError(404, '作品不存在!');

    let ac = await auth.getAc(req);
    let isOwner = doc.user == user;
    if (!ac.can('user').updateAny('art').granted && !isOwner) {
      throw createError(403, '权限不足');
    }

    doc.tags = tags;
    doc.epgs = epgs;
    doc.name = name;
    doc.desc = desc;
    await doc.save();
    res.json({
      msg: 'ok'
    })
  })().catch(next)
});






////////other-apis//////


router.get('/agg/tags', function (req, res, next) {
  (async function () {
    let tags = await models.Art.aggregate([
      { $project: { tags: 1 } },
      { $unwind: '$tags' },
      {
        $group: {
          _id: '$tags',
          count: { $sum: 1 }
        }
      },
      { $sort: { count: -1 } },
    ]);
    tags = tags.map(t => ({ value: t._id, label: t._id }));
    res.json(tags);
  })().catch(next)
});





module.exports = router;
