/* Copyright (c) 2006 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package sample.gbase.cmdline;

import com.google.api.gbase.client.AttributeHistogram;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.api.gbase.client.MetadataEntryExtension;
import com.google.api.gbase.client.AttributeHistogram.UniqueValue;
import com.google.gdata.util.ServiceException;

import java.io.IOException;
import java.net.URL;

/**
 * This class demonstrates how to retrieve Google Base metadata
 * using the client library of the Google Base data API.
 *
 * The tool implemented by this class will connect to Google Base, 
 * run the request and display some results.
 */
public class MetadataExample extends Example {

  /**
   * Runs the example.
   */
  public static void main(String[] args) throws IOException, ServiceException {
    String queryString = null;
    
    args = init(args, "Google-MetadataExample-1.0");
    
    // Process command-line arguments
    if (args.length == 1) {
      queryString = args[0];
    } else {
      System.err.println("Invalid argument count.");
      System.err.println("Expected one argument:");
      System.err.println(" query");
      System.exit(1);
    }

    queryMetadata(queryString);
  }

  /**
   * Retrieves and prints the list of the most used attributes used by
   * the items that match a query.
   * 
   * @param queryString a Google Base Query Language query
   */
  private static void queryMetadata(String queryString) 
      throws IOException, ServiceException {
    // Create a query URL from the given arguments
    URL url = urlFactory.getAttributesFeedURL();
    GoogleBaseQuery query = new GoogleBaseQuery(url);
    query.setGoogleBaseQuery(queryString);

    // Display the URL generated by the API
    System.out.println("Sending request to: " + query.getUrl());

    try {
      GoogleBaseFeed feed = service.query(query);
      // Print the items
      printMetadataFeed(feed);
    } catch (ServiceException e) {
      printServiceException(e);
    }
  }
  
  /**
   * Prints each metadata item in the feed to the output.
   * Uses {@link #printMetadataEntry(GoogleBaseEntry)}.
   *
   * @param feed a Google Base data API metadata feed
   */
  private static void printMetadataFeed(GoogleBaseFeed feed) {
    if (feed.getTotalResults() == 0) {
      System.out.println("No matches.");
      return;
    }
    for (GoogleBaseEntry entry : feed.getEntries()) {
      printMetadataEntry(entry);
    }
  }

  /**
   * Prints a few relevant attributes and the values of the attribute histogram 
   * of a metadata GoogleBaseEntry item.
   * 
   * @param entry a Google Base data API metadata entry
   */
  private static void printMetadataEntry(GoogleBaseEntry entry) {
    MetadataEntryExtension metadata = entry.getGoogleBaseMetadata();
    AttributeHistogram attributeHistogram = metadata.getAttributeHistogram();
    System.out.println(attributeHistogram.getAttributeName() + 
        " (" + attributeHistogram.getAttributeType().getName() + "): " +
        "valueCount=" + attributeHistogram.getTotalValueCount() + " - " + 
        entry.getId());
    for (UniqueValue value : attributeHistogram.getValues()) {
      System.out.println(value.getValueAsString() + 
          " count=" + value.getCount());
    }
  }
}
