import re
import logging

log = logging.getLogger("interp")

from interp.grid import grid as basegrid, cell

from subprocess import Popen, PIPE

def get_qdelaunay_dump(g):
  """
    pass in interp.grid g, and get back lines from a qhull triangulation:

    qdelaunay Qt f
  """
  cmd = 'qdelaunay Qt f'
  p = Popen(cmd.split(), bufsize=1, stdin=PIPE, stdout=PIPE)
  so, se = p.communicate(g.for_qhull())
  for i in so.splitlines():
    yield i

def get_qdelaunay_dump_str(g):
  return "\n".join(get_qdelaunay_dump(g))

def get_index_only(g):
  cmd = 'qdelaunay Qt i'
  p = Popen(cmd.split(), bufsize=1, stdin=PIPE, stdout=PIPE)
  so, se = p.communicate(g.for_qhull())
  for i in so.splitlines():
    yield i

def get_index_only_str(g):
  return "\n".join(get_index_only(g))

class dgrid(basegrid):
  cell_re = re.compile(r'''
                            -\s+(?P<cell>f\d+).*?
                            vertices:\s(?P<verts>.*?)\n.*?
                            neighboring\s facets:\s+(?P<neigh>[\sf\d]*)
                         ''', re.S|re.X)

  vert_re  = re.compile(r'''
                            (p\d+)
                         ''', re.S|re.X)

  def __init__(self, verts, q = None):
    self.dim = len(verts[0])
    basegrid.__init__(self, verts,q)
    self.construct_connectivity()

  def construct_connectivity(self):
    """
      a call to this method prepares the internal connectivity structure.

      this is part of the __init__ for a interp.grid.delaunay.grid, but can be
      called from any grid object
    """
    log.info('start')
    qdelaunay_string = get_qdelaunay_dump_str(self)

    with open('/tmp/qdel.out', 'w') as of:
      of.write(qdelaunay_string)

    cell_to_cells = []
    for matcher in dgrid.cell_re.finditer(qdelaunay_string):
      d = matcher.groupdict()

      cell_name          = d['cell']
      verticies          = d['verts']
      neighboring_cells  = d['neigh']

      cur_cell = cell(cell_name)
      self.cells[cell_name] = cur_cell

      for v in dgrid.vert_re.findall(verticies):
        vertex_index = int(v[1:])
        cur_cell.add_vert(vertex_index)
        self.cells_for_vert[vertex_index].append(cur_cell)

      nghbrs = [(cell_name, i) for i in  neighboring_cells.split()]
      cell_to_cells.extend(nghbrs)
    log.debug(cell_to_cells)

    for rel in cell_to_cells:
      if rel[1] in self.cells:
        self.cells[rel[0]].add_neighbor(self.cells[rel[1]])

    log.debug(self.cells)
    log.info('end')
