# -*- coding: utf-8 -*-
# PROJECT : picopico
# TIME    : 17-4-20 下午4:15
# AUTHOR  : youngershen <younger.x.shen@gmail.com>
import re


def parse():
    path = './location.txt'
    file = open(path)
    location = []
    for line in file.readlines():
        array = list(filter(lambda s: s if s else None, line.split(' ')))
        if len(array) == 2:
            code = array[0].strip()
            name = array[1].strip()
            if re.match(r'^[0-9]{2}0000$', code):
                entity = {
                    'model': 'account.location',
                    'pk': code,
                    'fields':
                        {
                            'name': name,
                            'parent_id': None
                        }
                }
                location.append(entity)

            if re.match(r'^[0-9]{3}[1-9]+00$', code):
                parent_id = code[:2] + '0000'
                entity = {
                    'model': 'account.location',
                    'pk': code,
                    'fields':
                        {
                            'name': name,
                            'parent_id': parent_id
                        }
                }
                location.append(entity)

            if re.match(r'^[0-9]{5}[1-9]+$', code):
                parent_id = code[:4] + '00'
                entity = {
                    'model': 'account.location',
                    'pk': code,
                    'fields':
                        {
                            'name': name,
                            'parent_id': parent_id
                        }
                }
                # location.append(entity)

    import json
    json_str = json.dumps(location)

    with open('./location.json', 'w+') as f:
        f.write(json_str)

if __name__ == '__main__':
    parse()
