# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import csv, prettytable
from typing import Dict, Tuple
from .Enums import ActionEnum, RecordTypeEnum
from .PerfPoint import PerfPoint

class PerfData:
    def __init__(self) -> None:
        self._type_count : Dict[Tuple[ActionEnum, RecordTypeEnum], int] = dict()
        self._points : Dict[Tuple[ActionEnum, RecordTypeEnum, str], PerfPoint] = dict()

    def get(self, action : ActionEnum, record_type : RecordTypeEnum, record_uuid : str) -> PerfPoint:
        point_key = (action, record_type, record_uuid)
        point = self._points.get(point_key)
        if point is None:
            point = PerfPoint(action, record_type, record_uuid)
            self._points[point_key] = point
            type_key = (action, record_type)
            self._type_count[type_key] = self._type_count.get(type_key, 0) + 1
        return point

    def to_csv(self, filepath : str) -> None:
        point : PerfPoint = self._points.values()[0]
        keys = point.to_dict().keys()
        with open(filepath, 'w', newline='', encoding='UTF-8') as csv_file:
            dict_writer = csv.DictWriter(csv_file, keys)
            dict_writer.writeheader()
            dict_writer.writerows(self._points)

    def stats_to_str(self) -> str:
        field_names = ['action', 'record_type', 'count']
        pt_stats = prettytable.PrettyTable(field_names=field_names, sortby='count', reversesort=True)
        for f in field_names[0:2]: pt_stats.align[f] = 'l'
        for f in field_names[2:3]: pt_stats.align[f] = 'r'
        for (action,record_type),count in self._type_count.items():
            pt_stats.add_row([action.value, record_type.value, count])
        return pt_stats.get_string()
