import  utils
from stores.project_store import ProjectStore
from models.project_data import SubProjectModel, SubProjectItemModel


class DataSend:
    def __init__(self):
        self._logger= utils.get_logger()
        self._project_store= ProjectStore()

    def send_by_project(self, sub_project: SubProjectModel) -> bool:
        try:

            self._logger.info(f"开始发送数据，项目：{sub_project.sub_project_name}[{sub_project.project_id}_{sub_project.id}]")
            self._project_store.update_sub_project_status(sub_project.id, 23)
            data_list = self._project_store.query_sub_project_items_by_project(sub_project.id, with_empty=False)
            for data in data_list:
                self.send_data(data)
            self._project_store.update_sub_project_status(sub_project.id, 33)
            self._logger.info(f"发送数据成功，项目：{sub_project.sub_project_name}[{sub_project.project_id}_{sub_project.id}] 共发送{len(data_list)}条")
            return True
        except Exception as e:
            self._logger.error(f"发送数据失败，项目：{sub_project.sub_project_name}[{sub_project.project_id}_{sub_project.id}]，错误信息：{e}")
            self._project_store.update_sub_project_status(sub_project.id, 13)
            return False

    def send_by_item_id(self, item_id: int) -> bool:
        data = self._project_store.query_sub_project_item_by_id(item_id)
        if data:
            return self.send_by_item(data)
        return False

    def send_by_item(self, item: SubProjectItemModel) -> bool:
        try:
            self._logger.info(f"开始发送数据，项目：{item.id}")
            if self.send_data(item):
                self._logger.info(f"发送数据成功，项目：{item.id}")
                return True
            return False
        except Exception as e:
            self._logger.error(f"发送数据失败，项目：{item.id}，错误信息：{e}")
            return False

    def send_data(self, data: SubProjectItemModel) -> bool:
        try:
            self._logger.debug(f"开始远程请求发送数据，数据：{data}" )
            self._project_store.update_sub_project_item_send_status(data.id, 1)

            self._project_store.update_sub_project_item_send_status(data.id, 2)
        except Exception as e:
            self._logger.error(f"发送数据失败，数据：{data}，错误信息：{e}")
            self._project_store.update_sub_project_item_send_status(data.id, 3)
            return False