/* global Venue */
'use strict';

const _ = require('lodash');
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
const Sequelize = require('sequelize');
const models = require('../../core/models');

function modelAssociationsToArray(model) {
    const result = [];

    if (typeof model !== 'function' || typeof model.associations !== 'object') {
        throw new Error("Model should be an object with the 'associations' property.");
    }

    Object.keys(model.associations).forEach((key) => {
        const association = {};

        // all needed information in the 'options' object
        if (model.associations[key].hasOwnProperty('options')) {
            association[key] = model.associations[key] //.options;
        }

        result.push(association);
    });

    return result;
}

function findModelAssociationByForeignIdentifier(model, foreignId) {

    if (typeof model !== 'function' || typeof model.associations !== 'object') {
        throw new Error("Model should be an object with the 'associations' property.");
    }

    Object.keys(model.associations).forEach((key) => {
        if (model.association[key].foreignIdentifier === foreignId) {
            const accessors = model.association[key].accessors;
            return {
                name: model.association[key].as,
                type: model.association[key].associationType,
                accessors: accessors,
                countFunc: accessors['count'],
                getFunc: accessors['get'],
            }
        }
    });

    return false;
}

function foundModelAssociation(model, associationName) {
    
    let result = false;

    if (typeof model !== 'function' || typeof model.associations !== 'object') {
        throw new Error("Model should be an object with the 'associations' property.");
    };

    Object.keys(model.associations).forEach((key) => {   
        const nameAs = model.associations[key].as;
        if (nameAs.toUpperCase() == associationName.toUpperCase()) {
            const item = model.associations[key];           
            const accessors = item.accessors;
            result = {
                name: item.as,
                type: item.associationType,
                accessors: accessors,
                countFunc: accessors['count'],
                getFunc: accessors['get'],
            }
        }
    })

    return result;
}

function extractParams(params) {
    const result = [];
    
    Object.keys(params).forEach((key, item) => {
        result[key] = item
    });
    return result;
}

const extraMethods = {
};

module.exports = generateService(models.Value, extraMethods);