#!/usr/bin/env python
# coding: utf-8

"""
Copyright (C) 2017 Jacksgong(jacksgong.com)

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 re
from okcat.terminalcolor import colorize, allocate_color, BLACK

__author__ = 'JacksGong'


class Trans:
    trans_msg_map = None
    trans_tag_map = None
    hide_msg_list = None
    trans_msg_regex_map = None

    def __init__(self, trans_msg_map, trans_tag_map, hide_msg_list):
        self.trans_msg_map = trans_msg_map
        self.trans_tag_map = trans_tag_map
        self.hide_msg_list = hide_msg_list
        self._compile_trans_msg_regex()

    def _compile_trans_msg_regex(self):
        """
        预处理 trans_msg_map，将正则表达式编译并存储
        如果 key 以 / 开头和结尾，则认为是正则表达式
        否则作为普通字符串处理（保持向下兼容）
        """
        if self.trans_msg_map is None:
            self.trans_msg_regex_map = None
            return

        self.trans_msg_regex_map = {}
        for key in self.trans_msg_map:
            if len(key) >= 2 and key.startswith('/') and key.endswith('/'):
                # 正则表达式：去掉首尾的 /
                regex_pattern = key[1:-1]
                try:
                    compiled_regex = re.compile(regex_pattern)
                    self.trans_msg_regex_map[key] = compiled_regex
                except re.error:
                    # 如果编译失败，作为普通字符串处理
                    self.trans_msg_regex_map[key] = None
            else:
                # 普通字符串
                self.trans_msg_regex_map[key] = None

    def trans_msg(self, msg):
        if self.trans_msg_map is None:
            return msg

        for key in self.trans_msg_map:
            compiled_regex = self.trans_msg_regex_map.get(key) if self.trans_msg_regex_map else None
            
            if compiled_regex is not None:
                # 使用正则表达式匹配
                match = compiled_regex.search(msg)
                if match:
                    value = self.trans_msg_map[key]
                    # 如果 value 以 @ 开头，表示在匹配文本后面插入
                    if value.startswith('@'):
                        # 去掉 @ 前缀
                        actual_value = value[1:]
                        # 找到匹配文本的结束位置
                        match_end = match.end()
                        # 在匹配文本后面插入转换值
                        colored_value = colorize(actual_value, fg=allocate_color(actual_value))
                        return u'%s | %s | %s' % (msg[:match_end], colored_value, msg[match_end:])
                    else:
                        # 原有行为：在消息开头插入
                        return u'| %s | %s' % (colorize(value, fg=allocate_color(value)), msg)
            else:
                # 使用普通字符串前缀匹配（保持向下兼容）
                if msg.startswith(key):
                    value = self.trans_msg_map[key]
                    return u'| %s | %s' % (colorize(value, fg=allocate_color(value)), msg)

        return msg

    def trans_tag(self, tag, msg):
        if self.trans_tag_map is None or tag is None:
            return msg

        for key in self.trans_tag_map:
            if key in tag:
                prefix = self.trans_tag_map[key]
                return u'%s %s' % (colorize(prefix, bg=allocate_color(prefix)), msg)

        return msg

    def hide_msg(self, msg):
        if self.hide_msg_list is None:
            return msg

        # print("get hide msg list: %s and len(%d)" % (self.hide_msg_list, len(msg)))
        # if msg.__len__() > 100:
        #     return msg

        for gray_msg in self.hide_msg_list:
            if msg.startswith(gray_msg):
                return colorize(msg, fg=BLACK)

        return msg
