import os
from sys import path, version
from types import new_class
from .tree import load_json, dump_json


def simple_list_md_load(p):
    with open(p, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        result = []
        for line in lines:
            item = line.strip('\n')
            result.append(item)
        return result


def simple_list_md_dump(p, lines):
    with open(p, 'w', encoding='utf-8') as f:
        f.write('\n'.join(lines))


def simple_py_load(p):
    with open(p, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        author = ''
        titles = []
        contents = []
        codes = []
        space_id = 0
        max_space_id = 0
        for i, line in enumerate(lines):
            item = line.strip('\n')
            if i == 0:
                pass
            elif i == 1:
                author = item[5:]
            elif i == 2:
                titles.append(item[5:])
            elif i == 3:
                contents.append(item[5:])
            elif item.startswith('#'):
                contents.append(item[2:])
            else:
                if item.strip() == '':
                    codes.append({
                        'space_id': space_id,
                        'code': item
                    })
                    if max_space_id < space_id:
                        max_space_id = space_id
                    space_id += 1
                else:
                    codes.append({
                        'space_id': -1,
                        'code': item
                    })

        strip_codes = []
        for line in codes:
            if line['space_id'] == 0 or line['space_id'] == max_space_id:
                pass
            else:
                strip_codes.append(line['code'])

        return {
            'author': author,
            'title': '\n'.join(titles),
            'contents': contents,
            'codes': strip_codes,
        }


class MDWalker():

    def __init__(self, root) -> None:
        self.root = root

    def walk(self):
        for base, dirs, files in os.walk(self.root):
            for file in files:
                if file[-3:] == '.py':
                    print(file)
                    py_file = os.path.join(base, file)
                    py = simple_py_load(py_file)
                    md_file = os.path.join(base, file.replace('.py', '.md'))
                    json_file = os.path.join(
                        base, file.replace('.py', '.json'))

                    print(py_file)
                    print(md_file)
                    print(json_file)

                    if os.path.exists(md_file):
                        j = load_json(json_file)
                        j['source'] = j['source'].replace('.py', '.md')
                        dump_json(json_file, j, True, True)
                        continue

                    md = []
                    self.emit_head(md, py)
                    self.emit_template(md, py)
                    self.emit_answer(md, py)
                    self.emit_options(md, py)
                    simple_list_md_dump(md_file, md)

                    if os.path.exists(json_file):
                        j = load_json(json_file)
                        if j.get('one_line'):
                            del j['one_line']
                        if j.get('multiline'):
                            del j['multiline']
                        j['author'] = py['author']
                        j['notebook_enable'] = True
                        j['source'] = j['source'].replace('.py', '.md')
                        dump_json(json_file, j, True, True)

    def emit_head(self, md, py):
        title = py['title']
        contents = py['contents']
        codes = py['codes']
        md.append(f'# {title}')
        md.append('')
        for content in contents:
            md.append(content)
        md.append('')
        md.append('```python')
        for code in codes:
            md.append(code)
        md.append('```')
        md.append('')
        md.append('请选出下列能**正确**实现这一功能的选项。')
        md.append('')

    def emit_template(self, md, py):
        codes = py['codes']
        md.append(f'## template')
        md.append('')
        md.append('```python')
        for code in codes:
            md.append(code)
        md.append('```')
        md.append('')

    def emit_answer(self, md, py):
        md.append(f'## 答案')
        md.append('')
        md.append('```python')
        md.append('')
        md.append('```')
        md.append('')

    def emit_options(self, md, py):
        md.append(f'## 选项')
        md.append('')

        for tag in ['A', 'B', 'C']:
            md.append(f'### {tag}')
            md.append('')
            md.append('```python')
            md.append('')
            md.append('```')
            md.append('')
