import re

import numpy as np

from .. import femio


class AnsysEntity(femio.FEMEntity):
    """FEMEntity of ANSYS version."""

    def __init__(self, file_names, read_mesh_only=False):
        """Initialize FrontISTREntity object.

        Args:
            file_names: List of strings indicating file names. No need to
                include "include" files.
            read_mesh_only: Bool. If true, read mesh (nodes and elements) and
                ignore material data, results and so on. Default is False.
        """
        super().__init__(file_names, read_mesh_only)
        self._read_ansys()
        raise ValueError(self.__dict__)

        # str_data = self._read_str_data()
        # str_data = self._expand_include(str_data, 'msh')
        # str_data = self._expand_include(str_data, 'cnt')
        # print('Parsing data')
        # self._read_cnt_solution_type(str_data['cnt'])
        # self._read_msh(str_data['msh'])
        # if not self.read_mesh_only:
        #     self._read_cnt(str_data['cnt'])
        #     self._read_res(str_data['res'])
        # self._resolve_assignments()

    def _read_ansys(self):
        n_file = len(self.file_names)
        if n_file > 2:
            raise ValueError(
                    "len(file_names) should be < 3 ({} given)".format(n_file))
        self._read_ansys_cdb()
        if n_file == 2:
            self._read_ansys_res()
        else:
            self.nodal_data = {}
        self.elemental_data = {}

    def _read_ansys_cdb(self):
        file_name = self.file_names[0]
        # self._check_ext(file_name, 'cdb')
        lines = self._read_file(file_name)

        str_nodes = self._extract_ansys_data(lines, '^N,', name='nodes')
        raise ValueError(str_nodes)
        self.nodes = femio.FEMAttribute('NODE', str_nodes, 1, (2, None))

        str_elements = self._extract_ansys_data(lines, '^EN,', name='elements')
        self.elements = \
            femio.FEMAttribute('ELEMENT', str_elements, 1, (2, None), int)

    def _extract_ansys_data(self, lines, exp_data, name=None):
        re_data = re.compile(exp_data)
        str_data = np.array(
                [line for line in lines if re_data.match(line)])
        return str_data

    def _read_ansys_res(self):
        with open(self.file_names[1], 'r') as f:
            lines = f.read().splitlines()[1:]

        str_displacements = np.array([line for line in lines])
        self.nodal_data = \
            {'DISPLACEMENT': femio.FEMAttribute(
                'DISPLACEMENT', str_displacements, 0, (1, None), float)}

    def _read_file(self, file_name):
        with open(file_name, 'r') as f:
            lines = np.array([line.strip() for line in f.read().splitlines()])
        return lines

    def _check_ext(self, file_name, extension):
        """Check the specified file name has the correct extension."""
        exp = re.compile(r'\.' + extension)
        if not exp.search(file_name):
            raise ValueError("{} is not {} file".format(file_name, extension))
