# read_bragg_reflections_from_out
import re, pandas as pd, math
from io import StringIO


class BraggContainer:
  def __init__(self, outfilepath, wavelength):
    """ searches an out file for bragg reflections generated by FullProf

    returns:
      dictionary:
        keys: phase names
        values: pd.DataFrame with information generated by FullProf

    """


    """ this indicator show when to start collecting the bragg reflection information from the out file """
    indicator = "--------------------------------------------------------------------------------------------------------------"
    """ this indicator showns when we terminate the search """
    indicator2 = "     -----------------------------------------------------"
    header = "No.  Code     H   K   L  Mult     Hw         2theta      Icalc       Iobs      Sigma      HwG     HwL       ETA       d-hkl        CORR"
    phases = []
    self.dfs = dict()
    lines = []
    phase_num = 0
    if_first = True
    stop_all = False
    with open(outfilepath,"r") as reading:
      for line in reading:
        if stop_all:
          break
        if indicator in line:
          if if_first:
            phase = reading.__next__()
            if_first = False
            phases.append( phase )
          # clean phase
          line=reading.__next__()
          line=reading.__next__()
          lines.append("")
          while True:
            try:
              line = reading.__next__()
            except StopIteration:
              break
            if header in line:
              reading.__next__()
              continue
            elif indicator in line:
              phase = reading.__next__()
              phases.append( phase )
              break
            elif indicator2 in line:
              stop_all = True
              break
            lines[-1]+=line

    for phase,line in zip(phases,lines):
      phase = phase.strip().split(" Phase name: ")[-1]
      load = StringIO(line)
      self.dfs[phase] = pd.read_csv(load, sep="\s+", names = header.strip().split())
      self.dfs[phase]["q-space"] = math.pi * 4 / wavelength * ( (math.pi / 180 / 2 * self.dfs[phase]["2theta"]).apply(math.sin) )
