'use strict';

var lodashLang = require('lodash/lang');
var lodashString = require('lodash/string');

var hasValue = function(val) {
    var found = false;

    if (Array.isArray(val)) {
        for (var i = 0; i < val; i++) {
            if (val[i]) {
                found = true;
            }
        }
    } else if (val) {
        found = true;
    }

    return found;
};

/*
 check whether the geojson has any values. This currently only works with basic addresses with coordinates and properties. It will
 need to be improved to work with more complex geojson structures like polygons
 */
var hasValues = function(value) {
    var found = false;

    if (value && value.features) {
        var features = value.features;

        for (var i = 0; i < features.length && !found; i++) {
            // ignore the type parameter, because a type alone isn't enough to say there is a value

            // check the properties
            if (features[i].properties) {
                for (var key in features[i].properties) {
                    if (features[i].properties.hasOwnProperty(key)) {
                        if (features[i].properties[key]) {
                            found = hasValue(features[i].properties[key]);

                            if (found) {
                                break;
                            }
                        }
                    }
                }
            }

            // check the geometry
            if (!found && features[i].geometry && features[i].geometry.coordinates) {
                for (var j = 0; j < features[i].geometry.coordinates.length; j++) {
                    if (features[i].geometry.coordinates[j]) {
                        if (lodashLang.isString(features[i].geometry.coordinates[j])) {
                            if (lodashString.trim(features[i].geometry.coordinates[j]) !== "") {
                                found = true;
                                break;
                            }
                        } else {
                            found = true;
                            break;
                        }
                    }
                }
            }
        }
    }

    return found;
};

module.exports = {
    hasValues: hasValues
};