import os
import re
import signal
import subprocess
import sys
import time
import traceback
import psutil
import platform


def monitor_libreoffice():
    pids = psutil.pids()
    for pid in pids:
        try:
            process = psutil.Process(pid)
            if process.username() == "appuser":
                if re.search("libreoffice", process.exe()):
                    if time.time() - process.create_time() >= 120:
                        print("=========================================")
                        print("process", pid, process.exe())
                        comm = "kill -9 " + str(pid)
                        subprocess.call(comm, shell=True)
                        print("killed", pid)
                        print("=========================================")
        except:
            continue


def office_convert(src_path, dest_path, target_format, retry_times=3):
    uid1 = src_path.split(os.sep)[-1].split(".")[0]
    dest_file_path = dest_path + uid1 + "." + target_format
    src_format = src_path.split(".")[-1]

    # 重试转换
    for i in range(retry_times):
        # 调用Win下的libreoffice子进程
        if platform.platform() == "Windows":
            soffice = 'C:\\Program Files\\LibreOfficeDev 5\\program\\soffice.exe'
            comm_list = [soffice, '--headless', '--convert-to', target_format, src_path,
                         '--outdir', dest_path+os.sep]
            try:
                p = subprocess.call(comm_list, timeout=30*(i+2))
            except:
                continue

        # 调用Linux下的libreoffice子进程
        else:
            # 先杀libreoffice进程
            # monitor_libreoffice()

            # 再调用转换
            # _dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
            # _dir = os.path.abspath(_dir) + os.sep
            _dir = None
            for _path in sys.path:
                if 'convert_soft' in str(_path):
                    _dir = _path
                    break
            if not _dir:
                print("no libreoffice!")
                return [-3]
            libreoffice_dir = _dir + os.sep + 'libreoffice' + os.sep + 'program' \
                              + os.sep + 'soffice'
            comm_list = [libreoffice_dir, '--headless', '--convert-to', target_format, src_path,
                         '--outdir', dest_path+os.sep]
            try:
                p = subprocess.call(comm_list, timeout=30*(i+2))
            except:
                print(src_format + ' to ' + target_format + ' Failed! Retry...', i, 'times')
                print(traceback.print_exc())
                continue

        # 执行失败，重试
        if not os.path.exists(dest_file_path):
            print(src_format + ' to ' + target_format + ' Failed! Retry...', i, 'times')
            continue
        # 执行成功，跳出循环
        else:
            break

    # 重试后还未成功
    if not os.path.exists(dest_file_path):
        print(src_format + ' to ' + target_format + ' failed!')
        return [-3]

    return dest_file_path
