import os
import threading
import time

from flask import Flask, send_from_directory
import flask
from flask_cors import CORS

from program_public_tools import ProgramPublicTools


class LocalFileService(object):
    def __init__(self):
        self.filename_list = ["信号发生器.pdf", "直流电源.pdf", "万用表.pdf", "直流电子负载.pdf", "示波器.pdf",
                              "高压放大器.pdf"]
        self.__host = "127.0.0.1"
        self.__port = ProgramPublicTools.find_available_server_port(number=1, address=self.__host, start_port=9500)[0]
        self.__app = Flask(__name__)
        CORS(self.__app)
        self.__setup_routes()
        self.__thread = None
        self.__start_flag: bool = False

    def __setup_routes(self):
        @self.__app.route("/documents/<filename>")
        def route_serve_pdf(filename):
            return self.__serve_pdf(filename)

    def __serve_pdf(self, filename):
        print("========filename: ", filename)
        if filename not in self.filename_list:
            flask.abort(404)
        current_file_path = os.path.realpath(__file__)
        current_dir = os.path.dirname(current_file_path)
        parent_dir = os.path.dirname(current_dir)
        file_path = os.path.join(parent_dir, "source", filename)
        print("file_path:", file_path)
        if not os.path.isfile(file_path):
            flask.abort(404)
        return send_from_directory(os.path.dirname(file_path), os.path.basename(file_path))

    def __start_flask(self):
        self.__app.run(port=self.__port)

    def start(self):
        if self.__start_flag is False:
            self.__start_server()
            self.__start_flag = True
        return self.get_server_info()

    def __start_server(self):
        self.__thread = threading.Thread(target=self.__start_flask)
        self.__thread.daemon = True
        self.__thread.start()
        return self.get_server_info()

    def get_server_info(self):
        return self.__host, self.__port
