import config
from PyPDF2 import PdfMerger
from pathlib import Path
import re
import json


def pdf_merge(base_dir: str, report_name):
    report_prefix = re.sub(r'\[([^\]]+)\]', '', report_name)
    target = f"{base_dir}/{report_prefix}_0.pdf"
    if Path(target).exists():
        Path(target).unlink()
    pdfs = [f for f in Path(base_dir).glob(report_prefix + '*.pdf')]
    if len(pdfs) > 0:
        with PdfMerger() as merger:
            for pdf in sorted(pdfs, key=lambda f: f.stat().st_mtime):
                merger.append(pdf)
            merger.write(target)


def get_reports(reports_file, folder):
    with open(reports_file, 'r') as frh:
        reports = json.load(frh)
    return [r['name'] for r in reports if r['path'].startswith(folder)]


def merge_reports_in_folder(cfg: config.Config, folder='Team Content/ReportOutput'):
    reports = get_reports(cfg.cognos11.reports_file, folder)
    for r in reports:
        print(r)
        pdf_merge(cfg.portal_dir + '/ReportOutput', r)


if __name__ == '__main__':
    merge_reports_in_folder(config.Config())
