'use strict';

const utilHttpStatus =  require('../../shared/utils/UtilHttpStatus');
const utilCustomComponent = require('../../server/utils/UtilCustomComponent');
const lodashString = require('lodash/string');
const componentService = require('../database/dataServices/ComponentService');

/**
 * load the component doc.
 */
exports.loadComponentDoc = function(req, res) {
  const userId = req.user.documentId;
  const componentName = req.params.componentName;

  //process the request
  const customComponent = {
    componentName: componentName
  };

  utilCustomComponent.getComponent(customComponent, userId).then(
    function successFunc(component) {
      if (!component) {
        res.json(utilHttpStatus.NOT_FOUND);
      } else {
        res.json(component);
      }
    },
    function errorFunc(err) {
      res.json(utilHttpStatus.NOT_FOUND);
    }
  );
};

exports.loadVendorLibrary = async (req, res) => {
  const userId = req.user.documentId;
  const name = req.params.name; // name or documentId

  try {
    const result = await componentService.getVendorLibrary(name, userId);
    if (result.length) {
      res.json(result[0]);
    } else {
      res.status(utilHttpStatus.NOT_FOUND).send(`Vendor library: ${name} not found!`);
    }
  } catch(err) {
    res.status(utilHttpStatus.INTERNAL_SERVER_ERROR).send(err.message);
  }
};

exports.loadVendorLibraries = async (req, res) => {
  const userId = req.user.documentId;
  try {
    const result = await componentService.getVendorLibraries(userId);
    res.json(result);
  } catch(err) {
    res.status(utilHttpStatus.INTERNAL_SERVER_ERROR).send(err.message);
  }
};
