import random as ra
import json as j
import os
import string as st

seed=None
#Fuckin' Androids
p=os.path.dirname(os.path.abspath(__file__))

def genbank(seed=None,sets=[0,1]):
 with open(os.path.join(p,'puzzles.json')) as b:
  a=j.load(b)
 if seed:
  a=[b for b in a if b['index'] not in seed]
 a=[b for b in a if b['set'] in sets]
 ra.shuffle(a)
 out=sorted(a[0:10],key=lambda a:a['cost'])
 if not seed:
  seed=[]
 seed2=seed+[chip['index'] for chip in out]
 out=(out,seed2)
 return out

def startgame(sets=[0,1]):
 global seed
 a,b=genbank(sets=sets)
 seed=b
 return a

def swapchip(chipin):
 global seed
 if not seed:
  print("You need to start a game first!")
  return False
 with open(os.path.join(p,'puzzles.json')) as b:
  a=j.load(b)
 try:
  inchip=(chip for chip in a if strip(chip['name'])==strip(chipin)).__next__()
 except:
  print('No such chip!')
  return False
 if inchip['index'] in seed:
  print('You\'ve already used that chip!')
  return False
 seed.append(inchip['index'])
 return inchip

def scramble(sets=[0,1]):
 global seed
 if not seed:
  print("You need to start a game first!")
  return False
 a,b=genbank(seed,sets)
 seed=b
 return a

#Some utility functions below.
def colourise(colour):
 colours={1:'Brown',2:'Red',4:'Blue',8:'Purple'}
 if not colour: return 'Grey'
 return ' '.join([col for ind,col in colours.items() if ind&colour])

def strip(strong):
 return ''.join(a for a in strong.lower() if a in st.digits+st.ascii_lowercase)