#!/usr/bin/env python
# -*- coding: utf-8 -*-
##################################################################
#
# Copyright (c) 2023 CICV, Inc. All Rights Reserved
#
##################################################################
"""
@Authors:           zhanghaiwen, yangzihao
@Data:              2024/02/21
@Last Modified:     2024/02/21
@Summary:           The template of custom indicator.
"""

"""
设计思路：

"""

import math
import pandas as pd
import numpy as np
from common import zip_time_pairs, continuous_group
from log import logger

"""import functions"""


# custom metric codes
class CustomMetric(object):
    def __init__(self, all_data, case_name):
        self.data = all_data
        self.optimal_dict = self.data.config
        self.case_name = case_name
        self.markline_df = pd.DataFrame(columns=['start_time', 'end_time', 'start_frame', 'end_frame', 'type'])
        self.graph_list = []

        self.df = pd.DataFrame()
        self.ego_df = pd.DataFrame()
        self.df_ica = pd.DataFrame()

        self.percentage_accel = 0

        self.result = {
            "name": "合理加减速度占比",
            "value": [],
            # "weight": [],
            "tableData": {
                "avg": "",  # 平均值，或指标值
                "max": "",
                "min": ""
            },
            "reportData": {
                "name": "合理加减速度占比（%）",
                # "legend": [], # 如果有多个data，则需要增加data对应的说明，如：["横向加速度", "纵向加速度"]
                "data": [],
                "markLine": [],
                "range": [],
            },
            "statusFlag": {}
        }
        self.run()
        print(f"合理加减速度占比: {self.result['value']}")

    def data_extract(self):
        self.df = self.data.object_df
        self.ego_df = self.data.ego_data
        self.df_ica = self.ego_df[self.ego_df['ICA_status'] == "Only_Longitudinal_Control"].copy()  # 数字3对应ICA的Active
        # self.df_ica = self.df[self.df['ACC_status'] == "Shut_off"].copy()  # 数字3对应ICA的Active
        # self.df_ica = self.df[self.df['ACC_status'] == "Active"].copy()  # 数字3对应ICA的Active

        if self.df_ica.empty:
            self.result['statusFlag']['function_ICA'] = False
        else:
            self.result['statusFlag']['function_ICA'] = True

    def data_analyze(self):
        col_list = ['simTime', 'simFrame', 'playerId', 'v', 'accel', 'lon_acc_roc']  # target_id
        df = self.df_ica[col_list].copy()
        count_accel_in_range = 0
        total_accel_frames = 0

        self.graph_list = df['accel'].values.tolist()
        filtered_data = df[(df['accel'] >= -5) & (df['accel'] <= 4)]
        count_accel_in_range = count_accel_in_range + len(filtered_data)
        total_accel_frames = total_accel_frames + len(df)
        self.percentage_accel = (count_accel_in_range / total_accel_frames) * 100

        self.result['value'] = [round(self.percentage_accel, 3)]
        print(f"percentage_accel: {self.percentage_accel}")

    def markline_statistic(self):
        pass

    def report_data_statistic(self):
        time_list = self.ego_df['simTime'].values.tolist()
        graph_list = [x for x in self.graph_list if not np.isnan(x)]
        self.result['tableData']['avg'] = f'{np.mean(graph_list):.2f}' if graph_list else 0
        self.result['tableData']['max'] = f'{max(graph_list):.2f}' if graph_list else 0
        self.result['tableData']['min'] = f'{min(graph_list):.2f}' if graph_list else 0

        zip_vs_time = zip_time_pairs(time_list, self.graph_list)
        self.result['reportData']['data'] = zip_vs_time

        # self.markline_statistic()
        # markline_slices = self.markline_df.to_dict('records')
        self.result['reportData']['markLine'] = []

        self.result['reportData']['range'] = [0, 100]

    def run(self):
        # logger.info(f"Custom metric run:[{self.result['name']}].")
        logger.info(f"[case:{self.case_name}] Custom metric:[percentage_accel:{self.result['name']}] evaluate.")

        try:
            self.data_extract()
        except Exception as e:
            logger.error(f"[case:{self.case_name}] Custom metric:{self.result['name']} data extract ERROR!", e)

        try:
            self.data_analyze()
        except Exception as e:
            logger.error(f"[case:{self.case_name}] Custom metric:{self.result['name']} data analyze ERROR!", e)

        try:
            self.report_data_statistic()
        except Exception as e:
            logger.error(f"[case:{self.case_name}] Custom metric:{self.result['name']} report data statistic ERROR!", e)

# if __name__ == "__main__":
#     pass
