# /*
#  * Copyright 2024 KylinSoft Co., Ltd.
#  *
#  * This program is free software: you can redistribute it and/or modify it under
#  * the terms of the GNU General Public License as published by the Free Software
#  * Foundation, either version 3 of the License, or (at your option) any later
#  * version.
#  *
#  * This program is distributed in the hope that it will be useful, but WITHOUT
#  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
#  * details.
#  *
#  * You should have received a copy of the GNU General Public License along with
#  * this program. If not, see <https://www.gnu.org/licenses/>.
#  */

import fitz  # PyMuPDF
from .base_parser import BaseParser

class PDFParser(BaseParser):
    def parser(self, file_path) -> list:
        """
        同时解析PDF文件中的文本和表格，并将它们合并到一个列表中。
        :return: 包含每页内容（文本和表格）的列表
        """
        pdf = fitz.open(file_path)
        content = []

        for page_num in range(pdf.page_count):
            page = pdf.load_page(page_num)
            results = self._parse_page(page)
            if results == ['']:
                continue
            else:
                content.extend(results)
        texts = ",".join(content)
        return texts

    def _parse_page(self, page) -> list:
        """
        解析单个页面的文本和表格。
        :param page: PyMuPDF 页面对象
        :return: 包含文本和表格数据的列表
        """
        # 提取文本
        text = page.get_text("text").strip()
        text = ''.join(text)

        # 提取表格
        tables = []
        # blocks = page.get_text("dict")["blocks"]
        # for block in blocks:
        #     if block["type"] == 0:
        #         table_data = []
        #         for line in block["lines"]:
        #             row_data = [span["text"] for span in line["spans"]]
        #             table_data.append(", ".join(row_data))
        #         tables.extend(table_data)
        # 将文本和表格合并到一个列表中
        combined_data = [text] + tables
        result = "".join(combined_data)
        return [result]

if __name__ == '__main__':
    DocxParser = PDFParser()
    paras = DocxParser.parser('/home/wangyan/操作系统大会演示素材v0.2/团建策划资料/怀柔1日-水上闯关团建方案-pptx(2).pdf')
    print(paras)
