# -*- coding: utf-8 -*-
"""
Base definitions for models of programs.

** under construction **
"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import collections

from grako.util import asjson, asjsons
from grako.exceptions import SemanticError
from grako.ast import AST

EOLCOL = 50


class Node(object):
    """ Base class for model nodes
    """

    inline = True

    def __init__(self, ctx=None, ast=None, parseinfo=None):
        super(Node, self).__init__()
        self._ctx = ctx
        self._parseinfo = parseinfo
        if isinstance(ast, AST):
            self._parseinfo = ast.parseinfo if not parseinfo else None

        self._parent = None
        self._adopt_children(ast)
        self.__postinit__(ast)

    def __postinit__(self, ast):
        if isinstance(ast, AST):
            for name, value in ast.items():
                if hasattr(self, name):
                    name = name + '_'
                setattr(self, name, value)

    @property
    def parent(self):
        return self._parent

    @property
    def line(self):
        info = self.line_info
        if info:
            return info.line

    @property
    def col(self):
        info = self.line_info
        if info:
            return info.col

    @property
    def ctx(self):
        return self._ctx

    @property
    def context(self):
        return self._ctx

    @property
    def parseinfo(self):
        return self._parseinfo

    @property
    def line_info(self):
        if self.parseinfo:
            return self.parseinfo.buffer.line_info(self.parseinfo.pos)

    @property
    def text(self):
        if self.parseinfo:
            text = self.parseinfo.buffer.text
            return text[self.parseinfo.pos:self.parseinfo.endpos]

    @property
    def comments(self):
        if self.parseinfo:
            return self.parseinfo.buffer.comments(self.parseinfo.pos)