#!/usr/bin/env python

from mmCif import mmcifIO
import sys
import cPickle as pickle
import os

DICT = "mmcif_pdbx_v40.dic"
PICKLE = DICT[:DICT.rfind(".")] + ".pkl"

category = sys.argv[1]
results = []

if os.path.isfile(PICKLE):
    with open(PICKLE, "rb") as input:
       f = pickle.load(input)
else:
    infile = mmcifIO.CifFileReader(input='dictionary')
    f = infile.read(DICT)

    with open(PICKLE, "wb") as output:
        pickle.dump(f, output, pickle.HIGHEST_PROTOCOL)

#print f.getDataBlocks()[0].getSaveFrame("entity_poly").getCategories()
for f in f.getDataBlocks()[0].getSaveFrames():  
    x = f.setCategory("item").setItem("category_id")
    if x and x.value == category:
        item = f.getCategory("item")
        results.append((item.getItem("name").value, item.getItem("mandatory_code").value))

col_width = max(len(word) for row in results for word in row) + 2  # padding       

for r in results:
    print "".join(word.ljust(col_width) for word in r)
    

#infile = mmcifIO.CifFileReader(input='data')
#
#obj1 = infile.read('./blah.cif', output='cif_wrapper', ignore=['atom_site'])
#
#obj1 = obj1['1abc']
#print obj1._entity_poly.my_id
#obj1._entity_poly['bar'] = [0,9,8,7,6]
#
#
#obj2 = infile.read('./blah.cif', output='cif_file', ignore=['atom_site'])
#
#print obj2.getDataBlocks()[0].getCategories()[0]
#
#
#
#j = mmcifIO.CifFileWriter('./blah_out.cif')
#k = {'entity_poly': {"my_id":[1,2,3,4,5], "foo": ['a','b','c','d','e']},
#        "entry": {"id":"1abc"}}
#
#j.write(obj1)


