#!/usr/bin/python

import subprocess
import sys

def normalize(string):
  return string.replace(' ', '').lower()

def unicode_charmap(needle = ''):
  DATABASE = '/usr/share/unicode-character-database/UnicodeData.txt'
  needle = normalize(needle)
  with open(DATABASE, 'rb') as db:
    for line in db:
      [code, name, _] = line.decode('utf-8').split(';', 2)
      name = name.lower()
      if name.startswith('<'):
        pass
      elif needle in normalize(name):
        yield (code, name)

def format_unicode_charmap(charmap):
  screen = ''
  hits = 0
  for (code, name) in charmap:
    screen += chr(int(code, 16)) + ' U+' + code + ' ' + name.upper() + '\n'
    hits += 1
  return screen

def print_or_pager(string):
  rows = len(string.splitlines())
  isatty = sys.stdout.isatty()

  try:
    max_rows, _ = subprocess.check_output(['stty', 'size']).split()
  except:
    isatty = False

  if isatty and rows + 2 >= int(max_rows):
    less = subprocess.Popen(['less'], stdin=subprocess.PIPE)
    less.communicate(input=screen.encode('utf-8'))
  else:
    sys.stdout.write(screen)

  sys.stdout.flush()

HARDCODED = {
  'shrug': '¯\_(ツ)_/¯'
}

if __name__ == "__main__":
  if len(sys.argv) < 2:
    print('Usage: {} needle'.format(sys.argv[0]))
    sys.exit(1)
  if len(sys.argv) == 2 and sys.argv[1] in HARDCODED:
    print(HARDCODED[sys.argv[1]])
  else:
    needle = ' '.join(sys.argv[1 :])
    charmap = list(unicode_charmap(needle))
    if len(charmap) <= 0:
      print('No hits')
      sys.exit(2)
    else:
      screen = format_unicode_charmap(charmap)
      print_or_pager(screen)
