// announcement.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const mongoose = require('mongoose');
const SiteLink = mongoose.model('SiteLink');

const { URL } = require('url'); // jshint ignore:line
const favicon = require('favicon');

const { SiteService } = require('../../lib/site-lib');

class SiteLinkService extends SiteService {

  constructor (dtp) {
    super(dtp, module.exports);
  }

  middleware ( ) {
    return async (req, res, next) => {
      if (req.path.startsWith('/auth') || req.path.startsWith('/image') || req.path.startsWith('/manifest')) {
        return next();
      }
      res.locals.links = await this.getLinks();
      this.log.debug('site links', { count: res.locals.links.length, path: req.path });
      return next();
    };
  }

  async create (linkDefinition) {
    const link = new SiteLink();
    link.label = linkDefinition.label;
    link.url = linkDefinition.url;
    link.iconUrl = await this.getSiteFavicon(linkDefinition.url);

    if (linkDefinition.targetBlank) {
      link.target = '_blank';
    }
    await link.save();
    return link.toObject();
  }

  async update (link, linkDefinition) {
    const updateOp = { $set: { }, $unset: { } };

    updateOp.$set.label = linkDefinition.label;
    updateOp.$set.url = linkDefinition.url;
    updateOp.$set.iconUrl = await this.getSiteFavicon(linkDefinition.url);

    if (linkDefinition.targetBlank) {
      updateOp.$set.target = '_blank';
    } else {
      updateOp.$unset.target = 1;
    }

    return SiteLink.findOneAndUpdate({ _id: link._id }, updateOp, { new: true });
  }

  async getLinks ( ) {
    return SiteLink.find().sort({ label: 1 }).lean();
  }

  async getById (linkId) {
    return SiteLink.findOne({ _id: linkId }).lean();
  }

  async remove (link) {
    await SiteLink.deleteOne({ _id: link._id });
  }

  async getSiteFavicon (url) {
    return new Promise((resolve, reject) => {
      favicon(url, (err, iconUrl) => {
        if (err) {
          return reject(err);
        }
        return resolve(iconUrl);
      });
    });
  }
}

module.exports = {
  slug: 'site-link',
  name: 'siteLink',
  create: (dtp) => { return new SiteLinkService(dtp); },
};