'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);
    }
  );
};

/**
 * load the component directive script. The component will be sent as a directive that can be loaded automatically
 */
exports.loadComponent = function(req, res) {
  const userId = req.user.documentId;
  const componentName = req.params.componentName;

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

  function writeScript(component) {
    utilCustomComponent.buildComponentScript(component, userId).then(function (componentDirectiveScript) {
      res.type('.js');
      res.write(componentDirectiveScript);
      res.end();
    });
  }

  function writeErrorScript(componentName, errorMessage) {
    const component = {};

    component.name = componentName;
    component.componentLoadFunction = "function() {}";
    component.componentHtml = `
            <div class="form-group label-floating">
                <ft-label></ft-label>'
                <div class="form-control alert alert-danger" role="alert">
                    ${errorMessage}
                </div>
            </div>
        `;

    writeScript(component);
  }

  utilCustomComponent.getComponent(customComponent, userId)
    .then(function successFunc(component) {
      if (!component) {
        res.json(utilHttpStatus.NOT_FOUND);
      } else {
        testLoadFunction(component, (error, parsed) => {
          if (error) {
            let errorMessage = `Syntax error in ${componentName} : ${error.message}`;
            writeErrorScript(componentName, errorMessage);
          } else {
            writeScript(component);
          }
        });
      }

    }, function errorFunc(err) {
      let errorMessage = `Component not found: ${componentName}`;
      writeErrorScript(componentName, errorMessage);
    });
};

exports.loadComponentLibraryFunctions = function(req, res) {
  const userId = req.user.documentId;
  const serviceName = req.params.serviceName;

  function writeScript(component) {
    utilCustomComponent.buildComponentLibraryScript(component, serviceName).then(function (componentDirectiveScript) {
      res.type('.js');
      res.write(componentDirectiveScript);
      res.end();
    });
  }

  //process the request
  const componentLibraryDocs = [];
  componentLibraryDocs.push({
    name: serviceName
  });

  utilCustomComponent.getComponentLibraryDocuments(componentLibraryDocs, userId, serviceName).then(
    function successFunc(component) {
      if (!component) {
        res.json(utilHttpStatus.NOT_FOUND);
      } else {
        writeScript(component);
      }
    },
    function errorFunc(err) {
      res.status(utilHttpStatus.INTERNAL_SERVER_ERROR).send(err);
    }
  );
};

function testLoadFunction(component, callback) {
  try {
    const func = lodashString.trim(component.componentLoadFunction);
    eval("(" + func + ")");
    callback(null, true);
  } catch (error) {
    callback(error, false);
  }
}

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);
  }
};
