package com.mycompany.jerseyclient;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import java.util.List;

/** Class that handles all the communication with the RESTful web service
 * for manipulating remote system properties.
 */
public class DataProvider {
    private static WebResource propsResource = Client.create().resource(
            "http://localhost:8080/jerseyservice/webresources/properties");


    /** Sets the property of a given name to a given value.
     *
     * @param propertyName Name of the property to set or create.
     * @param propertyValue A new value of the property.
     */
    public static void setPropertyValue(String propertyName, String propertyValue) {
        // Send a PUT request with propertyValue in the content
        propsResource.path(propertyName).put(propertyValue);
    }

    /** Retrieves the value of a given property.
     *
     * @param propertyName Name of the property to retrieve the value of.
     * @return value of the property.
     */
    public static String getPropertyValue(String propertyName) {
        // Send a GET request to the appropriate URL
        PropertyBean property = propsResource.path(propertyName)
                .accept("application/xml").get(PropertyBean.class);
        return property.getValue();
    }

    /** Deletes the property of a given name.
     *
     * @param propertyName Name of the property to delete.
     */
    public static void deleteProperty(String propertyName) {
       // Send a delete request to the appropriate URL
       propsResource.path(propertyName).delete();
    }


    /** Retrieves names of all properties.
     *
     * @return array of names of the properties.
     */
    public static String[] getPropertyNames() {
        // Send a GET request - Jersey will automatically parse it and return
        // a list of PropertyBeans
        List<PropertyBean> properties = propsResource.accept("application/json")
                .get(new GenericType<List<PropertyBean>>() {});

        // Extract property names from the list of PropertyBeans
        String[] propNames = new String[properties.size()];
        int i = 0;
        for (PropertyBean property : properties) {
            propNames[i] = property.getName();
            i++;
        }
        return propNames;
    }
}
