import sys
from pathlib import Path
import configparser
import re

''' find the file match file Headers and sort in array.
    @return and array of files match Headers. return None if some file not find.
'''
def findNeedFiles(files, fileHeaders):
    
    fileHeaderCount = len(fileHeaders)
    
    # create empty array to keep file name.
    out_files = []
    for i in range(fileHeaderCount):
        out_files.append(None)
    
    # compare each file to header and record in out_files.
    for file in files:
        for i in range(fileHeaderCount):
            head = fileHeaders[i]
            name = file.name
            if (name[:len(head)] == head):
                out_files[i] = file
                break
    
    # check all not None.
    for f in out_files:
        if f is None:
            return None
    
    return out_files

# load a file into an array and remove all empty line.
def loadFile(fileName):
  p = open(fileName,'rt')
  lines = []
  for line in p.readlines():
    line = line.strip()
    if (line != ''):
      lines.append(line)
  return lines

# read ini file
configFileName = Path(sys.argv[0]).with_suffix('.ini')
config = configparser.ConfigParser()
config.read(configFileName, encoding = 'utf-8')
fileHeaders = re.split(' +', config['DEFAULT']['file_headers'].strip())

if (len(sys.argv) == 2):
  filePath = Path(sys.argv[1])
  fileList = list(filePath.glob('*'))
elif (len(sys.argv) == len(fileHeaders)+1):
  filePath = None
  fileList = []
  for i in range(1,len(fileHeaders)+1):
    fileList.append(Path(sys.argv[i]))
else:
  print(sys.argv[0] + ' <src file path or src files>\n')
  input('enter continue ......')
  quit()

# fine all files.
files = findNeedFiles(fileList, fileHeaders)
if files is None:
  print('lost some files\n');
  input('enter continue ......')
  quit()

# keep all file text into list lineData.
lineData = []
for file in files:
  lineData.append(loadFile(file))

# each NNNN with two empty line.
for i in range(len(files)):
    d = lineData[i]
    if (d[-1] == 'NNNN'):
        del d[-1]
        d.append('')
        d.append('NNNN')
        d.append('')

# write file
  
outPath = files[0].resolve().parent.parent
outfile = outPath / (files[0].stem[len(fileHeaders[0]):] + '_out.txt')
f = open(outfile,'wt')
for i in range(len(files)):
  f.write('\n'.join(lineData[i]))
  f.write('\n')
f.write('\n')
f.close()
