'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _async = require('async');

var _async2 = _interopRequireDefault(_async);

var _elementLayoutsService = require('../../services/elementLayoutsService');

var _elementLayoutsService2 = _interopRequireDefault(_elementLayoutsService);

var _appUtils = require('../../utils/appUtils');

var _appUtils2 = _interopRequireDefault(_appUtils);

var _winstonLogs = require('../../utils/winstonLogs');

var _winstonLogs2 = _interopRequireDefault(_winstonLogs);

var _underscore = require('underscore');

var _underscore2 = _interopRequireDefault(_underscore);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var multer = require('multer'); /*
                                 * *******************************************************************************
                                 *  * Copyright (c) 2018 Edgeworx, Inc.
                                 *  *
                                 *  * This program and the accompanying materials are made available under the
                                 *  * terms of the Eclipse Public License v. 2.0 which is available at
                                 *  * http://www.eclipse.org/legal/epl-2.0
                                 *  *
                                 *  * SPDX-License-Identifier: EPL-2.0
                                 *  *******************************************************************************
                                 *
                                 */

var path = require('path');
var fs = require('fs');

var imageDir = path.join(__dirname, '/../../../../client_uploads');

if (!fs.existsSync(imageDir)) {
  fs.mkdirSync(imageDir);
}

var storage = multer.diskStorage({
  destination: function destination(req, file, callback) {
    callback(null, __dirname + '/../../../../client_uploads');
  },
  filename: function filename(req, file, callback) {
    var fileExtension = path.extname(file.originalname);
    if (fileExtension == '.png' || fileExtension == '.jpg' || fileExtension == '.ico' || fileExtension == '.jpeg') {
      callback(null, req.params.moduleId + fileExtension);
    } else {
      callback('file is not an image.', null);
    }
  }
});

var upload = multer({
  storage: storage,
  limits: { fileSize: 64535 }
}).single('elementicon');

/***** Upload Element Icon EndPoint (Post: api/v2/authoring/element/icon/upload/moduleid/:moduleId ********/
var uploadElementIconEndPoint = function uploadElementIconEndPoint(req, res) {
  _winstonLogs2.default.info("Endpoint hit: " + req.originalUrl);

  var params = {};

  params.bodyParams = req.params;
  _winstonLogs2.default.info("Parameters:" + JSON.stringify(params.bodyParams));

  upload(req, res, function (err) {
    if (err) {
      if (err.code == 'LIMIT_FILE_SIZE') {
        return res.json({
          status: 'failure',
          error: 'file is larger than 64 KiB'
        });
      } else {
        return res.json({
          status: 'failure',
          error: err
        });
      }
    } else {
      if (!req || !req.file) {
        return res.json({
          status: 'failure',
          error: 'no file chosen'
        });
      }
      res.json({
        status: 'ok',
        fileName: req.file.filename
      });
    }
  });
};

/***** Delete Layout of Element EndPoint (Post: api/v2/authoring/element/module/delete/moduleid/:moduleId*****/
var deleteElementLayoutsEndPoint = function deleteElementLayoutsEndPoint(req, res) {
  _winstonLogs2.default.info("Endpoint hit: " + req.originalUrl);

  var params = {},
      layoutProps = {
    elementKey: 'bodyParams.moduleId'
  };

  params.bodyParams = req.params;
  _winstonLogs2.default.info("Parameters:" + JSON.stringify(params.bodyParams));

  _async2.default.waterfall([_async2.default.apply(_elementLayoutsService2.default.deleteElementLayoutsByElementKeys, layoutProps, params)], function (err, result) {
    _appUtils2.default.sendResponse(res, err, '', '', result);
  });
};

/***** Get Layout of Element EndPoint (Post: /api/v2/authoring/get/element/module/layout*****/
var getElementLayoutsEndPoint = function getElementLayoutsEndPoint(req, res) {
  _winstonLogs2.default.info("Endpoint hit: " + req.originalUrl);

  var params = {},
      layoutProps = {
    elementData: 'bodyParams.elementCatalog',
    field: 'ID',
    setProperty: 'elementLayouts'
  };

  params.bodyParams = req.body;
  _winstonLogs2.default.info("Parameters:" + JSON.stringify(params.bodyParams));

  _async2.default.waterfall([_async2.default.apply(_elementLayoutsService2.default.findElementLayoutsByElementKeys, layoutProps, params), outputData], function (err, result) {
    _appUtils2.default.sendResponse(res, err, 'layoutData', params.response, result);
  });
};

/************************ Extra Functions ************************************/
var outputData = function outputData(params, callback) {
  try {
    var response = [];
    _async2.default.eachSeries(params.bodyParams.elementCatalog, function (instance, cb) {
      var elementLayout = _underscore2.default.findWhere(params.elementLayouts, {
        elementKey: Number(instance.ID)
      });

      var element = {
        id: instance.ID,
        name: instance.name,
        fogTypeName: instance.fogTypeName,
        picture: instance.picture ? instance.picture : 'images/shared/default.png',
        layoutX: elementLayout.layoutX ? elementLayout.layoutX : 0,
        layoutY: elementLayout.layoutY ? elementLayout.layoutY : 0,
        isSelected: elementLayout.isSelected ? elementLayout.isSelected : 0
      };
      response.push(element);
      cb();
    }, function (err) {
      params.response = response;
      callback(null, params);
    });
  } catch (e) {
    _winstonLogs2.default.error(e);
  }
};

/***** Create Element Layout EndPoint (Post: api/v2/authoring/element/module/create *****/
var createElementLayoutsEndPoint = function createElementLayoutsEndPoint(req, res) {
  _winstonLogs2.default.info("Endpoint hit: " + req.originalUrl);

  var params = {};

  params.bodyParams = req.body;
  _winstonLogs2.default.info("Parameters:" + JSON.stringify(params.bodyParams));

  var layoutProps = {
    data: {
      elementKey: params.bodyParams.elementKey,
      isSelected: params.bodyParams.isSelected,
      layoutX: params.bodyParams.layoutX,
      layoutY: params.bodyParams.layoutY,
      picture: params.bodyParams.picture
    },
    setProperty: 'newElementLayout'
  };

  _async2.default.waterfall([_async2.default.apply(_elementLayoutsService2.default.createElementLayout, layoutProps, params)], function (err, result) {
    _appUtils2.default.sendResponse(res, err, '', '', result);
  });
};

/***** Update Element Layout EndPoint (Post: api/v2/authoring/element/module/layout/update *****/
var updateElementLayoutsEndPoint = function updateElementLayoutsEndPoint(req, res) {
  _winstonLogs2.default.info("Endpoint hit: " + req.originalUrl);

  var params = {};

  params.bodyParams = req.body;
  _winstonLogs2.default.info("Parameters:" + JSON.stringify(params.bodyParams));

  var layoutProps = {
    updatedData: {
      isSelected: params.bodyParams.isSelected,
      layoutX: params.bodyParams.layoutX,
      layoutY: params.bodyParams.layoutY,
      picture: params.bodyParams.picture
    },
    elementKey: 'bodyParams.elementKey'
  };

  _async2.default.waterfall([_async2.default.apply(_elementLayoutsService2.default.updateLayout, layoutProps, params)], function (err, result) {
    _appUtils2.default.sendResponse(res, err, '', '', result);
  });
};

exports.default = {
  createElementLayoutsEndPoint: createElementLayoutsEndPoint,
  getElementLayoutsEndPoint: getElementLayoutsEndPoint,
  updateElementLayoutsEndPoint: updateElementLayoutsEndPoint,
  uploadElementIconEndPoint: uploadElementIconEndPoint,
  deleteElementLayoutsEndPoint: deleteElementLayoutsEndPoint
};