#include <stdio.h>
#include "string_to_const_string.h"

/*
  Only one map type has been defined in the header, so all of the macros will
  point to these definitions. We can therefore safely use the macro names for
  all functions.

  `string_to_const_string.expanded.c` is identical to this file, except that
  the macros have been expanded there.
*/


#define FILTER_CHAR 'T'

/*
  Example of a traversal function. This will print each key-value pair in the
  trie on a separate line in the format "key -> value". No additional arguments
  are given when the traverse function is called va_args is ignored.
*/
int
print_key_and_value_pairs(
  string_to_const_string_key_data_t * key_data,
  string_to_const_string_key_size_t height,
  va_list args
)
{
  if (! RBT_VALUE_IS_NULL(key_data->node->value))
  {
    // We can use our own single statement here.
    printf("%.*s -> %s\n", (int) key_data->bytes, (char *) key_data->key, key_data->node->value);

    // Or we can use the previously defined macros to do the same thing.
//     RBT_KEY_FPRINT(stdout, key_data->key, key_data->bytes);
//     printf(" -> ");
//     RBT_VALUE_FPRINT(stdout, key_data->node->value);
//     printf("\n");
  }
  return 0;
}

/*
  Another example of a traversal function. Here the key-value pairs with values
  beginning with a given character are inserted into a target node.
*/
int
insert_by_value_first_char(
  string_to_const_string_key_data_t * key_data,
  string_to_const_string_key_size_t height,
  va_list args
)
{
  string_to_const_string_node_t * target_node;
  char c;

  target_node = va_arg(args, string_to_const_string_node_t *);
  // char is promoted to int when passed through a variadic function
  c = va_arg(args, int);
  if (! RBT_VALUE_IS_NULL(key_data->node->value) && (key_data->node->value)[0] == c)
  {
    string_to_const_string_node_query(target_node, key_data->key, key_data->bits, RBT_QUERY_ACTION_INSERT, key_data->node->value);
  }
  return 0;
}




/*
  Example of a filter function. This filters by values.
*/
int
filter_by_value_first_char(string_to_const_string_value_t * string_ptr, va_list args)
{
  char c;
  // char is promoted to int when passed through a variadic function
  c = (char) va_arg(args, int);
  return ((* string_ptr)[0] != c);
}



/*
  Example of a filter_with_key function. This filters by keys.
*/
int
filter_key_by_first_char(
  string_to_const_string_key_data_t * key_data,
  va_list args
)
{
  char c;
  // char is promoted to int when passed through a variadic function
  c = (char) va_arg(args, int);
  /*
    The filter_with_key function passes the internal key array to the filter
    function, so we must cast it to a string to compare characters.
  */
  return (((RBT_KEY_T) key_data->key)[0] != c);
}


/*
  Example of a string_to_const_string_with_prefix_subtree_do function.

  This function will receive a subtree of the tree passed to that function.
*/
void
count_subtree(
  string_to_const_string_node_t * node,
  va_list args
)
{
  const char * fmt;
  fmt = va_arg(args, const char *);
  printf(fmt, string_to_const_string_node_count(node));
}


int
main(int argc, char * * argv)
{
  int i;
  char prefix[1];

  string_to_const_string_value_t value;
  string_to_const_string_node_t * node, * copy, * new, * copy2;

  // Create the node.
  node = string_to_const_string_node_new();

  // Insert some values (countries mapped to capital cities).
  string_to_const_string_insert(node, "Georgia", "Tbilisi");
  string_to_const_string_insert(node, "Switzerland", "Bern");
  string_to_const_string_insert(node, "Estonia", "Tallinn");
  string_to_const_string_insert(node, "Liberia", "Monrovia");
  string_to_const_string_insert(node, "Togo", "Lome");
  string_to_const_string_insert(node, "Russia", "Moscow");
  string_to_const_string_insert(node, "Uganda", "Kampala");
  string_to_const_string_insert(node, "Greece", "Athens");
  string_to_const_string_insert(node, "Albania", "Tirane");
  string_to_const_string_insert(node, "Tanzania", "Dar es Salaam; Dodoma (legislative)");
  string_to_const_string_insert(node, "Belgium", "Brussels");
  string_to_const_string_insert(node, "Poland", "Warsaw");
  string_to_const_string_insert(node, "Grenada", "Saint George's");
  string_to_const_string_insert(node, "Vietnam", "Hanoi");
  string_to_const_string_insert(node, "Brazil", "Brasilia");
  string_to_const_string_insert(node, "Rwanda", "Kigali");
  string_to_const_string_insert(node, "Ecuador", "Quito");
  string_to_const_string_insert(node, "Algeria", "Algiers");
  string_to_const_string_insert(node, "Kiribati", "Tarawa Atoll");
  string_to_const_string_insert(node, "Finland", "Helsinki");
  string_to_const_string_insert(node, "Monaco", "Monaco");
  string_to_const_string_insert(node, "Nepal", "Kathmandu");
  string_to_const_string_insert(node, "Denmark", "Copenhagen");
  string_to_const_string_insert(node, "Kuwait", "Kuwait City");
  string_to_const_string_insert(node, "Argentina", "Buenos Aires");
  string_to_const_string_insert(node, "Nigeria", "Abuja");
  string_to_const_string_insert(node, "Montenegro", "Podgorica");
  string_to_const_string_insert(node, "Morocco", "Rabat");
  string_to_const_string_insert(node, "Somalia", "Mogadishu");
  string_to_const_string_insert(node, "Chile", "Santiago");
  string_to_const_string_insert(node, "Bosnia and Herzegovina", "Sarajevo");
  string_to_const_string_insert(node, "Hungary", "Budapest");
  string_to_const_string_insert(node, "The Gambia", "Banjul");
  string_to_const_string_insert(node, "Uruguay", "Montevideo");
  string_to_const_string_insert(node, "Chad", "N'Djamena");
  string_to_const_string_insert(node, "United Arab Emirates", "Abu Dhabi");
  string_to_const_string_insert(node, "Cape Verde", "Praia");
  string_to_const_string_insert(node, "Trinidad and Tobago", "Port-of-Spain");
  string_to_const_string_insert(node, "San Marino", "San Marino");
  string_to_const_string_insert(node, "Micronesia, Federated States of", "Palikir");
  string_to_const_string_insert(node, "Djibouti", "Djibouti");
  string_to_const_string_insert(node, "United States of America", "Washington D.C.");
  string_to_const_string_insert(node, "Congo, Democratic Republic of the", "Kinshasa");
  string_to_const_string_insert(node, "Italy", "Rome");
  string_to_const_string_insert(node, "Honduras", "Tegucigalpa");
  string_to_const_string_insert(node, "Costa Rica", "San Jose");
  string_to_const_string_insert(node, "Philippines", "Manila");
  string_to_const_string_insert(node, "Zimbabwe", "Harare");
  string_to_const_string_insert(node, "Venezuela", "Caracas");
  string_to_const_string_insert(node, "Qatar", "Doha");
  string_to_const_string_insert(node, "Turkey", "Ankara");
  string_to_const_string_insert(node, "Gabon", "Libreville");
  string_to_const_string_insert(node, "Spain", "Madrid");
  string_to_const_string_insert(node, "Luxembourg", "Luxembourg");
  string_to_const_string_insert(node, "Solomon Islands", "Honiara");
  string_to_const_string_insert(node, "Suriname", "Paramaribo");
  string_to_const_string_insert(node, "Korea, South", "Seoul");
  string_to_const_string_insert(node, "Mongolia", "Ulaanbaatar");
  string_to_const_string_insert(node, "Palau", "Melekeok");
  string_to_const_string_insert(node, "Croatia", "Zagreb");
  string_to_const_string_insert(node, "Mexico", "Mexico City");
  string_to_const_string_insert(node, "Bhutan", "Thimphu");
  string_to_const_string_insert(node, "Serbia", "Belgrade");
  string_to_const_string_insert(node, "Saudi Arabia", "Riyadh");
  string_to_const_string_insert(node, "Andorra", "Andorra la Vella");
  string_to_const_string_insert(node, "Cambodia", "Phnom Penh");
  string_to_const_string_insert(node, "Kosovo", "Pristina");
  string_to_const_string_insert(node, "Saint Lucia", "Castries");
  string_to_const_string_insert(node, "Romania", "Bucharest");
  string_to_const_string_insert(node, "Eritrea", "Asmara");
  string_to_const_string_insert(node, "El Salvador", "San Salvador");
  string_to_const_string_insert(node, "Slovenia", "Ljubljana");
  string_to_const_string_insert(node, "Comoros", "Moroni");
  string_to_const_string_insert(node, "Tunisia", "Tunis");
  string_to_const_string_insert(node, "Lesotho", "Maseru");
  string_to_const_string_insert(node, "Iceland", "Reykjavik");
  string_to_const_string_insert(node, "Liechtenstein", "Vaduz");
  string_to_const_string_insert(node, "Moldova", "Chisinau");
  string_to_const_string_insert(node, "United Kingdom", "London");
  string_to_const_string_insert(node, "Angola", "Luanda");
  string_to_const_string_insert(node, "Turkmenistan", "Ashgabat");
  string_to_const_string_insert(node, "Belize", "Belmopan");
  string_to_const_string_insert(node, "Korea, North", "Pyongyang");
  string_to_const_string_insert(node, "Nauru", "no official capital; government offices in Yaren District");
  string_to_const_string_insert(node, "Brunei", "Bandar Seri Begawan");
  string_to_const_string_insert(node, "France", "Paris");
  string_to_const_string_insert(node, "Iraq", "Baghdad");
  string_to_const_string_insert(node, "Burundi", "Bujumbura");
  string_to_const_string_insert(node, "Marshall Islands", "Majuro");
  string_to_const_string_insert(node, "Iran", "Tehran");
  string_to_const_string_insert(node, "Peru", "Lima");
  string_to_const_string_insert(node, "Ethiopia", "Addis Ababa");
  string_to_const_string_insert(node, "Haiti", "Port-au-Prince");
  string_to_const_string_insert(node, "Latvia", "Riga");
  string_to_const_string_insert(node, "Sao Tome and Principe", "Sao Tome");
  string_to_const_string_insert(node, "Bahrain", "Manama");
  string_to_const_string_insert(node, "Armenia", "Yerevan");
  string_to_const_string_insert(node, "Jordan", "Amman");
  string_to_const_string_insert(node, "Tajikistan", "Dushanbe");
  string_to_const_string_insert(node, "Samoa", "Apia");
  string_to_const_string_insert(node, "The Bahamas", "Nassau");
  string_to_const_string_insert(node, "Central African Republic", "Bangui");
  string_to_const_string_insert(node, "Cuba", "Havana");
  string_to_const_string_insert(node, "Barbados", "Bridgetown");
  string_to_const_string_insert(node, "Austria", "Vienna");
  string_to_const_string_insert(node, "Zambia", "Lusaka");
  string_to_const_string_insert(node, "Dominican Republic", "Santo Domingo");
  string_to_const_string_insert(node, "Malawi", "Lilongwe");
  string_to_const_string_insert(node, "Laos", "Vientiane");
  string_to_const_string_insert(node, "Malaysia", "Kuala Lumpur");
  string_to_const_string_insert(node, "Guatemala", "Guatemala City");
  string_to_const_string_insert(node, "Czech Republic", "Prague");
  string_to_const_string_insert(node, "Cote d'Ivoire", "Yamoussoukro (official); Abidjan (de facto)");
  string_to_const_string_insert(node, "Equatorial Guinea", "Malabo");
  string_to_const_string_insert(node, "Guinea-Bissau", "Bissau");
  string_to_const_string_insert(node, "Belarus", "Minsk");
  string_to_const_string_insert(node, "Sierra Leone", "Freetown");
  string_to_const_string_insert(node, "Senegal", "Dakar");
  string_to_const_string_insert(node, "Australia", "Canberra");
  string_to_const_string_insert(node, "Singapore", "Singapore");
  string_to_const_string_insert(node, "Norway", "Oslo");
  string_to_const_string_insert(node, "East Timor (Timor-Leste)", "Dili");
  string_to_const_string_insert(node, "Bolivia", "La Paz (administrative); Sucre (judicial)");
  string_to_const_string_insert(node, "Malta", "Valletta");
  string_to_const_string_insert(node, "Kazakhstan", "Astana");
  string_to_const_string_insert(node, "Cameroon", "Yaounde");
  string_to_const_string_insert(node, "Slovakia", "Bratislava");
  string_to_const_string_insert(node, "Japan", "Tokyo");
  string_to_const_string_insert(node, "Fiji", "Suva");
  string_to_const_string_insert(node, "Indonesia", "Jakarta");
  string_to_const_string_insert(node, "Saint Kitts and Nevis", "Basseterre");
  string_to_const_string_insert(node, "Antigua and Barbuda", "Saint John's");
  string_to_const_string_insert(node, "Guyana", "Georgetown");
  string_to_const_string_insert(node, "Ireland", "Dublin");
  string_to_const_string_insert(node, "Dominica", "Roseau");
  string_to_const_string_insert(node, "Netherlands", "Amsterdam; The Hague (seat of government)");
  string_to_const_string_insert(node, "Nicaragua", "Managua");
  string_to_const_string_insert(node, "Kyrgyzstan", "Bishkek");
  string_to_const_string_insert(node, "Libya", "Tripoli");
  string_to_const_string_insert(node, "Saint Vincent and the Grenadines", "Kingstown");
  string_to_const_string_insert(node, "Niger", "Niamey");
  string_to_const_string_insert(node, "Myanmar (Burma)", "Rangoon (Yangon); Naypyidaw or Nay Pyi Taw (administrative)");
  string_to_const_string_insert(node, "Botswana", "Gaborone");
  string_to_const_string_insert(node, "Maldives", "Male");
  string_to_const_string_insert(node, "Oman", "Muscat");
  string_to_const_string_insert(node, "Macedonia", "Skopje");
  string_to_const_string_insert(node, "Vanuatu", "Port-Vila");
  string_to_const_string_insert(node, "Bangladesh", "Dhaka");
  string_to_const_string_insert(node, "Panama", "Panama City");
  string_to_const_string_insert(node, "Tonga", "Nuku'alofa");
  string_to_const_string_insert(node, "Bulgaria", "Sofia");
  string_to_const_string_insert(node, "Mauritania", "Nouakchott");
  string_to_const_string_insert(node, "Lithuania", "Vilnius");
  string_to_const_string_insert(node, "Jamaica", "Kingston");
  string_to_const_string_insert(node, "Paraguay", "Asuncion");
  string_to_const_string_insert(node, "Israel", "Jerusalem*");
  string_to_const_string_insert(node, "Mauritius", "Port Louis");
  string_to_const_string_insert(node, "Ukraine", "Kyiv");
  string_to_const_string_insert(node, "New Zealand", "Wellington");
  string_to_const_string_insert(node, "Germany", "Berlin");
  string_to_const_string_insert(node, "China", "Beijing");
  string_to_const_string_insert(node, "Papua New Guinea", "Port Moresby");
  string_to_const_string_insert(node, "Mozambique", "Maputo");
  string_to_const_string_insert(node, "Colombia", "Bogota");
  string_to_const_string_insert(node, "Syria", "Damascus");
  string_to_const_string_insert(node, "Burkina Faso", "Ouagadougou");
  string_to_const_string_insert(node, "Pakistan", "Islamabad");
  string_to_const_string_insert(node, "Madagascar", "Antananarivo");
  string_to_const_string_insert(node, "Mali", "Bamako");
  string_to_const_string_insert(node, "Kenya", "Nairobi");
  string_to_const_string_insert(node, "Yemen", "Sanaa");
  string_to_const_string_insert(node, "Benin", "Porto-Novo");
  string_to_const_string_insert(node, "Lebanon", "Beirut");
  string_to_const_string_insert(node, "Sudan", "Khartoum");
  string_to_const_string_insert(node, "Taiwan", "Taipei");
  string_to_const_string_insert(node, "Namibia", "Windhoek");
  string_to_const_string_insert(node, "Cyprus", "Nicosia");
  string_to_const_string_insert(node, "Canada", "Ottawa");
  string_to_const_string_insert(node, "Ghana", "Accra");
  string_to_const_string_insert(node, "Portugal", "Lisbon");
  string_to_const_string_insert(node, "Afghanistan", "Kabul");
  string_to_const_string_insert(node, "Vatican City (Holy See)", "Vatican City");
  string_to_const_string_insert(node, "Swaziland", "Mbabane");
  string_to_const_string_insert(node, "Seychelles", "Victoria");
  string_to_const_string_insert(node, "South Sudan", "Juba (Relocating to Ramciel)");
  string_to_const_string_insert(node, "Sri Lanka", "Colombo; Sri Jayewardenepura Kotte (legislative)");
  string_to_const_string_insert(node, "Sweden", "Stockholm");
  string_to_const_string_insert(node, "Tuvalu", "Vaiaku village, Funafuti province");
  string_to_const_string_insert(node, "South Africa", "Pretoria (administrative); Cape Town (legislative); Bloemfontein (judiciary)");
  string_to_const_string_insert(node, "Thailand", "Bangkok");
  string_to_const_string_insert(node, "Congo, Republic of the", "Brazzaville");
  string_to_const_string_insert(node, "Egypt", "Cairo");
  string_to_const_string_insert(node, "Azerbaijan", "Baku");
  string_to_const_string_insert(node, "Uzbekistan", "Tashkent");
  string_to_const_string_insert(node, "Guinea", "Conakry");
  string_to_const_string_insert(node, "India", "New Delhi");

  // Print a representation of the tree.
  printf("Representation of the tree:\n");
  string_to_const_string_node_fprint(stdout, node, 0, 0);


  // Traverse all key-value pairs.
  printf("\nTraversal of all key-value pairs in the tree:\n");
  string_to_const_string_node_traverse_with_key(node, print_key_and_value_pairs);

  // Count the number of nodes.
  printf("\nCounting the number of insertions: %lu\n", string_to_const_string_node_count(node));

  // Make a copy of the tree and filter by *capitals* beginning with 'T', i.e.
  // by *value*.
  copy = string_to_const_string_node_copy(node);
  printf("\nCreating a copy of the tree and filtering for capitals beginning with '%c'.\n", FILTER_CHAR);
  string_to_const_string_node_filter(copy, filter_by_value_first_char, 0, FILTER_CHAR);

  // Print the filtered tree and its key-value pairs.
  string_to_const_string_node_fprint(stdout, copy, 0, 0);
  printf("\n");
  string_to_const_string_node_traverse_with_key(copy, print_key_and_value_pairs);

  // Count the number of nodes in the filtered tree.
  printf("\nCounting the number of insertions: %lu\n", string_to_const_string_node_count(copy));


  // Create a new tree and selectively insert countries beginning with 'T'.
  new = string_to_const_string_node_new();
  printf("\nCreating new tree for capitals beginning with '%c' using a traversal function.\nThe results should be the same as the filtered copy above.\n", FILTER_CHAR);
  string_to_const_string_node_traverse_with_key(node, insert_by_value_first_char, new, FILTER_CHAR);

  // Print this new tree and its key-value pairs.
  string_to_const_string_node_fprint(stdout, new, 0, 0);
  printf("\n");
  string_to_const_string_node_traverse_with_key(new, print_key_and_value_pairs);

  // Count the number of insertions.
  printf("\nCounting the number of insertions: %lu\n", string_to_const_string_node_count(new));


  // Compare the last two trees, which should be the same.
  printf("\nDoing a node by node comparison of the two previous trees: ");
  if (string_to_const_string_node_is_copy(copy, new))
  {
    printf("they are equivalent.\n");
  }
  else
  {
    printf("they are not equivalent. [error]\n");
  }


  // Show the actual bits stored in the node keys.
  printf("\nA representation of the previous tree showing key bits:\n");
  string_to_const_string_node_fprint(stdout, copy, 1, 0);


  // Look up the capitals of countries entered on the command line.
  if (argc > 1)
  {
    printf("\nLooking up requested capitals.\n");
  }
  for (i = 1; i < argc; i++)
  {
    value = string_to_const_string_retrieve(node, argv[i]);
    if (RBT_VALUE_IS_NULL(value))
    {
      printf("Unrecognized country: %s\n", argv[i]);
    }
    else
    {
      printf("The capital of %s is %s\n", argv[i], value);
    }
  }

  // Make another copy and filter countries beginning with 'T', i.e. filter by
  // key.
  copy2 = string_to_const_string_node_copy(node);
  printf("\nCreating another copy of the tree and filtering for countries beginning with '%c'.\n", FILTER_CHAR);
  string_to_const_string_node_filter_with_key(copy2, filter_key_by_first_char, 0, FILTER_CHAR);
  string_to_const_string_node_traverse_with_key(copy2, print_key_and_value_pairs);

  printf("\nCounting the number of countries that begin with '%c': %lu\n", FILTER_CHAR, string_to_const_string_node_count(copy2));



  /*
    Do essentially the same thing using a prefix-defined subtree. This will find
    the subtree of all keys that begin with 'T' and copy it to a separate tree.

    The first argument is the tree.

    The second is the prefix to find (the filter char, passed as a string).

    The third is the number of *bits* in the key to match.

    The fourth is the function to call with this subtree. Here will will count
    the number of entries in the subtree, i.e the number of countries beginning
    with 'T'.

    Arguments after the fourth are additional arguments to pass to that function
    along with the subtree.

    This could be used to copy the the subtree to another tree as well.
  */
  prefix[0] = FILTER_CHAR;
  if (
    ! string_to_const_string_with_prefix_subtree_do(
        node,
        (string_to_const_string_pin_t *) prefix, BITS_PER_BYTE,
        count_subtree, "\nCounting again using a prefix filter: %u\n"
      )
  )
  {
    printf("\nPrefix filter failed\n");
  }



  /*
    Print trees for each character filter. This was used to select the
    narrowest tree representation.
  char c;
  for (c = 'A'; c <= 'Z'; c ++)
  {
    copy = string_to_const_string_node_copy(node);
    string_to_const_string_node_filter(copy, filter_by_value_first_char, 0, c);
    printf("\nchar: %c\n", c);
    string_to_const_string_node_fprint(stdout, copy, 1, 0);
  }
  */

  /*
    Free everything.
  */
  string_to_const_string_node_free(node);
  string_to_const_string_node_free(copy);
  string_to_const_string_node_free(copy2);
  string_to_const_string_node_free(new);
  printf("done\n");
  return EXIT_SUCCESS;
}
