#!/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.stable_average_speed = None
        self.rise_time_cruise = None

        self.result = {
            "name": "定速巡航上升时间",
            "value": [],
            # "weight": [],
            "tableData": {
                "avg": "",  # 平均值，或指标值
                "max": "",
                "min": ""
            },
            "reportData": {
                "name": "定速巡航上升时间（s）",
                # "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 _get_first_change_index_cruise(self):
        """
        获取数据集中第一次巡航速度发生变化的索引。

        Args:
            无参数。

        Returns:
            Union[int, None]: 如果存在巡航速度发生变化的索引，则返回第一个发生变化的索引（int类型）；
            如果不存在，则返回None。

        """
        change_indices = self.df_ica[self.df_ica['set_cruise_speed'] != self.df_ica['set_cruise_speed'].shift()].index
        if not change_indices.empty:
            first_change_index = change_indices.min()
        else:
            first_change_index = None
        return first_change_index

    def _find_stable_speed_cruise(self, window_size, percent_deviation, set_value):
        """
        在给定的速度数据中查找稳定的巡航速度段，并计算该段的平均速度。

        Args:
            window_size (int): 滑动窗口的大小，表示用于计算平均速度的速度数据点数量。
            percent_deviation (float): 设定值的允许偏差百分比。
            set_value (float): 期望的稳定速度设定值。

        Returns:
            None

        """
        # speed_data = self.df['speedX'].values
        speed_data = self.df_ica['speedX'].values   #.tolist()
        deviation = set_value * (percent_deviation / 100)
        stable_start = None
        stable_average_speed = None

        for i in range(len(speed_data) - window_size + 1):
            window_data = speed_data[i:i + window_size]

            if all(set_value - deviation <= s <= set_value + deviation for s in window_data):
                if stable_start is None:
                    stable_start = i
                    stable_end = i + window_size - 1
                    stable_average_speed = np.mean(window_data)

                j = i + window_size
                while j < len(speed_data) - window_size + 1:
                    next_window_data = speed_data[j:j + window_size]

                    if all(set_value - deviation <= s <= set_value + deviation for s in next_window_data):
                        stable_end = j + window_size - 1
                        stable_average_speed = (stable_average_speed * (j - stable_start) + sum(next_window_data)) / (
                                j - stable_start + window_size)
                        j += window_size
                    else:
                        stable_start = j + window_size - 1
                        stable_end = i + window_size - 1
                        stable_average_speed = np.mean(window_data)
                        break

        # self.stable_start_time_cruise = self.df['simTime'].iloc[stable_start]
        self.stable_average_speed = stable_average_speed

    def _find_closest_time_stamp_cruise(self, df, target_speed, start_index):
        """
        在给定的数据帧df中，从start_index索引位置开始，查找与目标速度target_speed最接近的时间戳。

        Args:
            df (pd.DataFrame): 包含速度和时间戳等信息的数据帧，需要至少包含'speedX'和'simTime'两列。
            target_speed (float): 目标速度值，用于在数据帧中查找最接近此值的时间戳。
            start_index (int): 开始查找的索引位置，即在数据帧df中从该索引位置开始向后查找。

        Returns:
            pd.Timestamp: 与目标速度最接近的时间戳。

        """
        subset = df.loc[start_index + 1:]
        speed_diff = np.abs(subset['speedX'] - target_speed)
        closest_index = speed_diff.idxmin()
        closest_timestamp = subset.loc[closest_index, 'simTime']
        return closest_timestamp

    def data_analyze(self):
        first_change_index = self._get_first_change_index_cruise()

        set_cruise_speed = self.df_ica.loc[first_change_index, 'set_cruise_speed']
        self._find_stable_speed_cruise(window_size=4, percent_deviation=5, set_value=set_cruise_speed)

        initial_speed = self.df_ica.loc[first_change_index, 'speedX']

        target_speed_90 = initial_speed + (self.stable_average_speed - initial_speed) * 0.9
        target_speed_10 = initial_speed + (self.stable_average_speed - initial_speed) * 0.1

        timestamp_at_10 = self._find_closest_time_stamp_cruise(self.df_ica, target_speed_10, first_change_index)
        timestamp_at_90 = self._find_closest_time_stamp_cruise(self.df_ica, target_speed_90, first_change_index)

        print(f"Closest speed at 10% range from set speed: {timestamp_at_10}")
        print(f"Closest speed at 90% range from set speed: {timestamp_at_90}")

        self.rise_time_cruise = timestamp_at_90 - timestamp_at_10
        self.result['value'] = [round(self.rise_time_cruise, 3)]
        print(f"Rise time: {self.rise_time_cruise}")

    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'] = self.result['value'][0] if not self.df_ica.empty else '-'
        self.result['tableData']['max'] = '-'
        self.result['tableData']['min'] = '-'

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

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

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

    def run(self):
        # logger.info(f"Custom metric run:[{self.result['name']}].")
        logger.info(f"[case:{self.case_name}] Custom metric:[rise_time_cruise:{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
