/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
package com.urbancode.air.plugin.tfs

import groovy.json.JsonBuilder

public class MapBuilder {
    private Map labelValuesMap = new HashMap()

    public void set(def key, def value) {
        if (this.labelValuesMap[key]) {
            this.labelValuesMap[key].add(value)
        } else {
            this.labelValuesMap[key] = new HashSet()
            this.labelValuesMap[key].add(value)
        }
    }

    public void setIterable(def keyValueObjects, String keyMethods, String valueMethods) {
        keyValueObjects.each {
            set(it."${keyMethods}"(), it."${valueMethods}"())
        }
    }

    public void setIterable(def keyValueObjects) {
        keyValueObjects.each {
            set(it, it)
        }
    }

    public String getJSONString() {
        String result

        List rootJSONArray = new LinkedList()
        labelValuesMap.each {
            Map jsonObject = new HashMap()
            jsonObject = [label:it.key,value:it.value]
            rootJSONArray.add(jsonObject)
        }

        JsonBuilder jsonBuilder = new groovy.json.JsonBuilder()
        jsonBuilder(rootJSONArray)
        result = jsonBuilder.toString()

        return result
    }
}
