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

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

"""import functions"""


# def zip_time_pairs(time_list, zip_list):
#     zip_time_pairs = zip(time_list, zip_list)
#     zip_vs_time = [[x, y] for x, y in zip_time_pairs if not math.isnan(y)]
#     return zip_vs_time

# def continuous_group(df):
#     time_list = df['simTime'].values.tolist()
#     frame_list = df['simFrame'].values.tolist()
#
#     group_time = []
#     group_frame = []
#     sub_group_time = []
#     sub_group_frame = []
#
#     for i in range(len(frame_list)):
#         if not sub_group_time or frame_list[i] - frame_list[i - 1] <= 1:
#             sub_group_time.append(time_list[i])
#             sub_group_frame.append(frame_list[i])
#         else:
#             group_time.append(sub_group_time)
#             group_frame.append(sub_group_frame)
#             sub_group_time = [time_list[i]]
#             sub_group_frame = [frame_list[i]]
#
#     group_time.append(sub_group_time)
#     group_frame.append(sub_group_frame)
#     group_time = [g for g in group_time if len(g) >= 2]
#     group_frame = [g for g in group_frame if len(g) >= 2]
#
#     # 输出图表值
#     time = [[g[0], g[-1]] for g in group_time]
#     frame = [[g[0], g[-1]] for g in group_frame]
#
#     time_df = pd.DataFrame(time, columns=['start_time', 'end_time'])
#     frame_df = pd.DataFrame(frame, columns=['start_frame', 'end_frame'])
#
#     result_df = pd.concat([time_df, frame_df], axis=1)
#
#     return result_df


# def continous_judge(frame_list):
#     if not frame_list:
#         return 0
#
#     cnt = 1
#     for i in range(1, len(frame_list)):
#         if frame_list[i] - frame_list[i - 1] <= 3:
#             continue
#         cnt += 1
#     return cnt


# custom metric codes
class CustomMetric(object):
    def __init__(self, all_data, case_name):
        self.data = all_data
        self.case_name = case_name
        self.markline_df = pd.DataFrame(columns=['start_time', 'end_time', 'start_frame', 'end_frame', 'type'])
        self.result = {
            "name": "车道偏离漏预警次数(次)",
            "value": [],
            # "weight": [],
            "tableData": {
                "avg": "",  # 平均值，或指标值
                "max": "",
                "min": ""
            },
            "reportData": {
                "name": "车道线距离（m)",
                # "legend": [], # 如果有多个data，则需要增加data对应的说明，如：["横向加速度", "纵向加速度"]
                "data": [],
                "markLine": [],
                "range": [],
            }
        }
        self.run()

    def data_extract(self):
        self.ego_df = self.data.ego_data
        self.df_roadmark = self.data.road_mark_df
        line_dist_df = self.df_roadmark[(self.df_roadmark['id'] == 0) | (self.df_roadmark['id'] == 2)].copy()
        df = line_dist_df.groupby('simFrame').apply(lambda t: abs(t['lateralDist']).min()).reset_index()
        df.columns = ["simFrame", "line_dist"]
        self.ego_df = pd.merge(self.ego_df, df, on='simFrame', how='left')
        self.df = self.ego_df[['simTime', 'simFrame', 'LKA_status', 'line_dist']].copy()

    def data_analyze(self):
        ldw_df = self.df
        # count miss warning
        miss_warning_df = ldw_df[(ldw_df['line_dist'] <= 0.4) & (ldw_df['LKA_status'] != "Active")]
        miss_warning_frame_list = miss_warning_df['simFrame'].values.tolist()
        miss_warning_count = continous_judge(miss_warning_frame_list)
        self.result['value'].append(miss_warning_count)

    def markline_statistic(self):
        metric_df = self.df[['simTime', 'simFrame', 'line_dist']].copy()
        m_df = metric_df[metric_df['line_dist'] < 0.4]  # 与车道线距离过近
        m_df_continuous = continuous_group(m_df)
        m_df_continuous['type'] = 'LDW'
        self.markline_df = pd.concat([self.markline_df, m_df_continuous], ignore_index=True)

    def report_data_statistic(self):
        time_list = self.df['simTime'].values.tolist()
        line_dist_list = self.df['line_dist'].values.tolist()
        graph_list = [x for x in line_dist_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, line_dist_list)
        self.result['reportData']['data'] = zip_vs_time

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

        self.result['reportData']['range'] = f"[0, 0.4]"

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