/**************************************************************************************************
 *
 * ADOBE SYSTEMS INCORPORATED
 * Copyright 2018 Adobe Systems Incorporated
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the
 * terms of the Adobe license agreement accompanying it.  If you have received this file from a
 * source other than Adobe, then your use, modification, or distribution of it requires the prior
 * written permission of Adobe.
 *
 **************************************************************************************************/

/*jslint vars: true, node: true, plusplus: true, unparam: true, nomen: true, white: true */
/*global GLOBAL */
'use strict';

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

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

var UNSUPPORTED_EXTENSIONS = [ '.ai', '.svg' ];

var initialized = false, lib;

module.exports.initialize = function(callback) {
    if (initialized) {
        return callback("Module already initialized.");
    }

    var libraryPath;

    // Initialize and load the library
    if (os.platform() === 'darwin') {
        libraryPath = path.join(__dirname , '/native/Mac/NativeThumbnailGenerator/build/Release/libNativeThumbnailGenerator.dylib');
    } else if (os.platform() === 'win32') {
        // Use prefix \\?\ in order to workaround the MAX PATH LENGTH limitation (CCXC-1288)
        var dllsDir = '\\\\?\\' +  path.join(__dirname, '\\native\\Win\\NativeThumbnailGenerator\\build\\Release');
        libraryPath = path.join(dllsDir, 'NativeThumbnailGenerator.dll');

        // Add the DLL path to the PATH environment variable so that our dedendency DLLs get loaded)
        process.env['PATH'] = `${process.env.PATH};${dllsDir}`;
    }

    if (libraryPath) {
        try {
            lib = ffi.Library(libraryPath, {
                'initialize': ['void', []],
                'generateThumbnail': ['CString', ['CString', 'CString', 'int', 'int']],
                '_shutdown': ['void', []]
            });
            lib.initialize();
            initialized = true;
        } catch (error) {
            return callback(error);
        }
    }
    callback(undefined, initialized);
};

module.exports.getThumbnail = function(source, destination, width, height, callback) {
    if (!initialized) {
        return callback("Module has not been initialized.");
    }

    if (!lib) {
        return callback("Unsupported platform or configuration.");
    }

    if (!source || !destination) {
        return callback("Source or destination cannot be null");
    }

    if (!width || !height || width <= 0 || height <= 0) {
        return callback("Width and height must be a positive integer");
    }

    if (UNSUPPORTED_EXTENSIONS.includes(path.extname(source).toLowerCase())) {
        return callback("File type not supported: " + path.extname(source));
    }

    fs.exists(source, function (exists) {
        if (!exists) {
            return callback("File does not exist");
        }

        lib.generateThumbnail.async(path.normalize(source), path.normalize(destination), width, height, function (err, result) {
            callback(err || result);
        });
    });
};

module.exports.shutdown = function () {
    if (!initialized) {
        return callback("Module has not been initialized.");
    }

    if (!lib) {
        return callback("Unsupported platform or configuration.");
    }

    lib._shutdown();

    initialized = false;
    lib = undefined;
};
