import horse as h

boxes='─│┌┐└┘├┤┬┴┼'

def fancyprint(chips):
 print('\n'.join(list(map(lambda x:'{0} {1}'.format(x['cost'],x['name']),chips))))

def createtable(data):
 #Get the column widths
 colnum=len(data[0])
 #Gotta init this so I can iterate backwards
 colwidths=[0 for _ in range(colnum)]
 for row in data:
  i=colnum
  while i>0:
   #Can't forget this now.
   i-=1
   colwidths[i]=max(colwidths[i],len(str(row[i])))
 #Create header row
 table='┌{0}┐'.format('┬'.join(['─'*width for width in colwidths]))
 #Assume data[0] is the title row
 i=-1
 rowbuild=''
 while i<(colnum-1):
  i+=1
  rowbuild+='│{0}{1}'.format(data[0][i],' '*(colwidths[i]-len(str(data[0][i]))))
 table+='\n│{0}│'.format(rowbuild[1:])
 table+='\n├{0}┤'.format('┼'.join(['─'*width for width in colwidths]))
 #Now the final loop to do the rest of the table, then all I need is the bottom row.
 for row in data[1:]:
  i=-1
  rowbuild=''
  while i<(colnum-1):
   i+=1
   rowbuild+='│{0}{1}'.format(row[i],' '*(colwidths[i]-len(str(row[i]))))
  table+='\n│{0}│'.format(rowbuild[1:])
 table+='\n└{0}┘'.format('┴'.join(['─'*width for width in colwidths]))
 return table

def colourmap(chip):
 if type(chip['colour'])==type(1):
  chip['colour']=h.colourise(chip['colour'])

def fancify(bank):
 titles=list(bank[0])
 list(map(colourmap,bank))
 bank=[[a for _,a in chip.items()] for chip in bank]
 bank.insert(0,titles)
 print(createtable(bank))

bank=None
quit=False
while not quit:
 if bank and len(bank)>=10:
  fancify(bank)
  choice=input('What would you like to do?\nRe[s]tart a game, s[w]ap a chip, s[c]ramble the bank or [q]uit?\n')
 else:
  bank=None
  choice=input('Would you like to [s]tart a new game or [q]uit?\n')
 if choice.lower()=='q':
  quit=True
  continue
 elif choice.lower()=='s':
  bank=h.startgame()
 elif choice.lower()=='w':
  if not bank:
   print("You have to start a game first!")
   continue
  rem=input('What chip are you taking out? ')
  try:
   rem=(chip for chip in bank if h.strip(chip['name'])==h.strip(rem)).__next__()
  except:
   rem=False
  if rem:
   add=input('What chip are you putting in? ')
   add=h.swapchip(add)
   if add:
    bank.pop(bank.index(rem))
    bank.append(add)
    bank=sorted(bank,key=lambda a:a['cost'])
  else:
   print('Couldn\'t find that chip in the bank to remove!')
 elif choice.lower()=='c':
  if not bank:
   print("You have to start a game first!")
   continue
  bank=h.scramble()