from optparse import OptionParser

import os
import json
import codecs

import numpy as np


def main():
    usage = "%prog input_file output_file"
    parser = OptionParser(usage=usage)
    #parser.add_option('--keyword', dest='key', default=None,
    #                  help='Keyword argument: default=%default')
    #parser.add_option('--boolarg', action="store_true", dest="boolarg", default=False,
    #                  help='Keyword argument: default=%default')

    (options, args) = parser.parse_args()

    input_filename = args[0]
    output_filename = args[1]

    with codecs.open(input_filename, 'r', encoding='utf-8') as input_file:
        data = json.load(input_file)

    with codecs.open(output_filename, 'w', encoding='utf-8') as output_file:
        for sentence in data:
            tuples = []
            indices = []
            for token in sentence:
                index = int(token['index']) + 1
                edge_to_parent = token['edge_to_parent']
                if edge_to_parent is None:
                    edge_to_parent = 'ROOT'
                word = token['word']
                parent_index = token['parent_index']
                if parent_index is None:
                    parent_index = 0
                else:
                    parent_index = int(parent_index) + 1
                value = int(token['value'])
                tuples.append((index, word, value, parent_index, edge_to_parent))
                indices.append(index)
            order = np.argsort(indices)
            for i in order.tolist():
                t = tuples[i]
                output_string = u'{0}\t{1}\t{2}\t_\t_\t_\t{3}\t{4}\t_\t_\n'.format(t[0], t[1], t[2], t[3], t[4])
                output_file.write(output_string)
            output_file.write('\n')

if __name__ == '__main__':
    main()
