'use strict';

const AccessManager = require("../../../shared/access/AccessManager");

module.exports = {

    /**
     *
     * @param {*} documentWithKeys - the document to check the access keys on
     * @param {*} userDocumentId - the documentId of the account
     * @param {*} operation - the operation being performed from SharedConstants.OPERATION_TYPE values.
     * Eg. SharedConstants.OPERATION_TYPE_CREATE
     */
    checkAccess: function(documentWithKeys, userDocumentId, operation){ //Implements 12125

        //Not allowing to create documents when documentWithKeys is empty.  And allowing to create
        // if user has a create access based on noTemplateAccessKeys from server configuration
        if (!userDocumentId || (!documentWithKeys && operation !== SharedConstants.OPERATION_TYPE_CREATE)) {
            return Promise.resolve(true);
        }

        var noTemplateAccessKeyIds = [];
        if (operation === SharedConstants.OPERATION_TYPE_CREATE && !documentWithKeys){
            noTemplateAccessKeyIds = config.get("noTemplateAccessKeys");
            noTemplateAccessKeyIds = noTemplateAccessKeyIds ? noTemplateAccessKeyIds : [];
        }
        userDocumentId = userDocumentId.documentId ? userDocumentId.documentId : userDocumentId;

        const AccountService = require("../dataServices/AccountService");

        return AccountService.getAccountControlDocument(userDocumentId).then(function(userAccountControlDocument){

            return AccessManager.checkAccess(documentWithKeys, userAccountControlDocument, operation, noTemplateAccessKeyIds);

        });

    },

    getUserAccessKeysForOperation : function (userDocumentId, operation){

        userDocumentId = userDocumentId.documentId ? userDocumentId.documentId : userDocumentId;

        const AccountService = require("../dataServices/AccountService");

        return AccountService.getAccountControlDocument(userDocumentId).then(function(userAccountControlDocument){

            return AccessManager.getUserAccessKeysForOperation(userAccountControlDocument, operation);

        });
    },


    // Document access determined by comparing systemHeader.keyIds against the user's attachKeys.
    // A new document inherits keyIds from its template and from the user that created it.
    writeKeysToDocument: function writeKeysToDocument(document, template, userDocumentId){

        // If userDocumentId is the user object then use its documentId
        userDocumentId = userDocumentId.documentId ? userDocumentId.documentId : userDocumentId;

        const AccountService = require("../dataServices/AccountService");

        return AccountService.getAccountControlDocument(userDocumentId).then(function(userAccountControlDocument){

            AccessManager.writeKeysToDocument(document, template, userAccountControlDocument, config.get("defaultAttachKeys"));

        });

    }

};