/* 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.GoogleBaseAttributeId;
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.ItemTypeDescription;
import com.google.api.gbase.client.MetadataEntryExtension;
import com.google.gdata.util.ServiceException;

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

/**
 * This class demonstrates how to retrieve Google Base item types
 * 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 ItemTypesExample extends Example {

  /**
   * Runs the example.
   */
  public static void main(String[] args) throws IOException, ServiceException {
    String locale = null;
    String itemType = null;
    
    args = init(args, "Google-ItemTypesExample-1.0");
    
    if (args.length == 0) {
      // nothing to do
    } else if (args.length == 1) {
      locale = args[0];
    } else if (args.length == 2) {
      locale = args[0];
      itemType = args[1];
    } else {
      System.err.println("Invalid argument count.");
      System.err.println("Expected either two arguments, to get an itemtype:");
      System.err.println(" locale itemtype");
      System.err.println("or one argument, to get the itemtypes of a locale:");
      System.err.println(" locale");
      System.err.println("or no argument, to get the locales.");
      System.exit(1);
    }

    if (locale == null) {
      queryLocales();
    } else {
      if (itemType == null) {
        queryItemTypes(locale);
      } else {
        queryItemType(locale, itemType);
      }
    }
  }

  /**
   * Retrieves and prints the locales.
   * 
   */
  private static void queryLocales() 
      throws IOException, ServiceException {
    // Create a query URL
    URL url = urlFactory.getLocalesFeedURL();
    GoogleBaseQuery query = new GoogleBaseQuery(url);

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

    try {
      GoogleBaseFeed feed = service.query(query);
      // Print the locales
      for (GoogleBaseEntry entry : feed.getEntries()) {
        System.out.println(entry.getTitle().getPlainText());
      }
    } catch (ServiceException e) {
      printServiceException(e);
    }
  }
  
  /**
   * Retrieves and prints the item types Google suggests for a locale.
   * 
   * @param locale the locale to be analysed
   */
  private static void queryItemTypes(String locale) 
      throws IOException, ServiceException {
    // Create a query URL from the given arguments
    URL url = urlFactory.getItemTypesFeedURL(locale);
    GoogleBaseQuery query = new GoogleBaseQuery(url);

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

    try {
      GoogleBaseFeed feed = service.query(query);
      // Print the item types
      printItemTypeFeed(feed);
    } catch (ServiceException e) {
      printServiceException(e);
    }
  }
  
  /**
   * Retrieves and prints the attribute ids Google suggests for an item type of
   * a locale.
   * 
   * @param locale the locale of the item type
   * @param itemType the item type to be analysed
   */
  private static void queryItemType(String locale, String itemType) 
      throws IOException, ServiceException {
    // Create a query URL from the given arguments
    URL url = urlFactory.getItemTypesEntryURL(locale, itemType);

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

    try {
      GoogleBaseEntry entry = service.getEntry(url);
      // Print the item type
      printItemTypeEntry(entry);
    } catch (ServiceException e) {
      printServiceException(e);
    }
  }


  /**
   * Prints each itemtype item in the feed to the output.
   * Uses {@link #printItemTypeEntry(GoogleBaseEntry)}.
   *
   * @param feed a Google Base data API itemtypes feed
   */
  private static void printItemTypeFeed(GoogleBaseFeed feed) {
    if (feed.getTotalResults() == 0) {
      System.out.println("No matches.");
      return;
    }
    for (GoogleBaseEntry entry : feed.getEntries()) {
      printItemTypeEntry(entry);
    }
  }

  /**
   * Prints the name and the recommended attribute names of 
   * an itemtype GoogleBaseEntry item.
   * 
   * @param entry a Google Base data API itemtype entry
   */
  private static void printItemTypeEntry(GoogleBaseEntry entry) {
    MetadataEntryExtension metadata = entry.getGoogleBaseMetadata();
    ItemTypeDescription itemTypeDescription = metadata.getItemTypeDescription();
    System.out.println(itemTypeDescription.getName() + " - " + entry.getId());
    for (GoogleBaseAttributeId attrId : itemTypeDescription.getAttributeIds()) {
      System.out.println(attrId.getName() + 
          " (" + attrId.getType().getName() + ")");
    }
  }
}
