(function(tree) {
var _ = require('underscore');

// Given a style's name, attachment, definitions, and an environment object,
// return a stringified style for Mapnik
tree.StyleXML = function(name, attachment, definitions, env) {
    var existing = {};
    var image_filters = [], image_filters_inflate = [], direct_image_filters = [], comp_op = [], opacity = [];

    for (var i = 0; i < definitions.length; i++) {
        for (var j = 0; j < definitions[i].rules.length; j++) {
            if (definitions[i].rules[j].name === 'image-filters') {
                image_filters.push(definitions[i].rules[j]);
            }
            if (definitions[i].rules[j].name === 'image-filters-inflate') {
                image_filters_inflate.push(definitions[i].rules[j]);
            }
            if (definitions[i].rules[j].name === 'direct-image-filters') {
                direct_image_filters.push(definitions[i].rules[j]);
            }
            if (definitions[i].rules[j].name === 'comp-op') {
                comp_op.push(definitions[i].rules[j]);
            }
            if (definitions[i].rules[j].name === 'opacity') {
                opacity.push(definitions[i].rules[j]);
            }
        }
    }

    var rules = definitions.map(function(definition) {
        return definition.toXML(env, existing);
    });

    var attrs_xml = '';

    if (image_filters.length) {
        attrs_xml += ' image-filters="' + _.chain(image_filters)
            // prevent identical filters from being duplicated in the style
            .uniq(function(i) { return i.id; }).map(function(f) {
            return f.ev(env).toXML(env, true, ',', 'image-filter');
        }).value().join(',') + '"';
    }

    if (image_filters_inflate.length) {
        attrs_xml += ' image-filters-inflate="' + image_filters_inflate[0].value.ev(env).toString() + '"';
    }

    if (direct_image_filters.length) {
        attrs_xml += ' direct-image-filters="' + _.chain(direct_image_filters)
            // prevent identical filters from being duplicated in the style
            .uniq(function(i) { return i.id; }).map(function(f) {
            return f.ev(env).toXML(env, true, ',', 'direct-image-filter');
        }).value().join(',') + '"';
    }

    if (comp_op.length && comp_op[0].value.ev(env).value != 'src-over') {
        attrs_xml += ' comp-op="' + comp_op[0].value.ev(env).toString() + '"';
    }

    if (opacity.length && opacity[0].value.ev(env).value != 1) {
        attrs_xml += ' opacity="' + opacity[0].value.ev(env).toString() + '"';
    }
    var rule_string = rules.join('');
    if (!attrs_xml && !rule_string) return '';
    return '<Style name="' + name + '" filter-mode="first"' + attrs_xml + '>\n' + rule_string + '</Style>';
};

})(require('../tree'));
