-- args location string
DROP FUNCTION match_regions(TEXT);
CREATE OR REPLACE FUNCTION match(TEXT) RETURNS INT
AS $$
  # splitting location arguments, starting from the biggest element on the right
  places = args[0].rsplit(",").flip

  # for each given location name we try to match one from db
  for place in places:
    if len(matched_locs)>0: # if we have earlier locations, we try to match next within the smallest region children
      for search_loc in matched_locs:
        find_places = plpy.prepare("SELECT id FROM region WHERE id IN (SELECT RECURSIVE .. WHERE parentid = nod.id) AND 
plainto_tsquery($1,'english') @@ name_vector", ["text"])
        locs = plpy.execute(find_places, [place])
    else:
      find_places = plpy.prepare("SELECT id FROM region WHERE plainto_tsquery($1,'english') @@ name_vector ORDER BY 
regiongroupid DESC NULLS LAST", ["text"])
      locs = plpy.execute(find_places, [place])
    matched_locs.append(locs[0])
  

  return matched_locs[0]
$$ LANGUAGE plpythonu;
