######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#   Mark Pilgrim - port to Python
#   Shy Shalom - original C code
#   Proofpoint, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301  USA
######################### END LICENSE BLOCK #########################

from .charsetprober import CharSetProber
from .enums import ProbingState, MachineState


class MultiByteCharSetProber(CharSetProber):
    """
    MultiByteCharSetProber
    """

    def __init__(self, lang_filter=None):
        # 初始化函数，传入参数lang_filter
        super(MultiByteCharSetProber, self).__init__(lang_filter=lang_filter)
        # 调用父类的初始化函数
        self.distribution_analyzer = None
        # 初始化分布分析器
        self.coding_sm = None
        # 初始化编码状态机
        self._last_char = [0, 0]

        # 初始化最后一个字符
    def reset(self):
        # 重置函数
        super(MultiByteCharSetProber, self).reset()
        # 调用父类的重置函数
        if self.coding_sm:
            # 如果编码状态机存在
            self.coding_sm.reset()
            # 重置编码状态机
        if self.distribution_analyzer:
            # 如果分布分析器存在
            self.distribution_analyzer.reset()
            # 重置分布分析器
        self._last_char = [0, 0]

    @property
    def charset_name(self):
        raise NotImplementedError

    @property
    def language(self):
        raise NotImplementedError

    def feed(self, byte_str):
        # 遍历byte_str中的每个字节
        for i in range(len(byte_str)):
            # 获取当前字节的编码状态
            coding_state = self.coding_sm.next_state(byte_str[i])
            # 如果编码状态为错误，则记录错误信息，并将状态设置为NOT_ME
            if coding_state == MachineState.ERROR:
                self.logger.debug('%s %s prober hit error at byte %s',
                                  self.charset_name, self.language, i)
                self._state = ProbingState.NOT_ME
                break
            # 如果编码状态为确定，则将状态设置为FOUND_IT
            elif coding_state == MachineState.ITS_ME:
                self._state = ProbingState.FOUND_IT
                break
            # 如果编码状态为开始，则获取当前字符长度
            elif coding_state == MachineState.START:
                char_len = self.coding_sm.get_current_charlen()
                # 如果是第一个字节，则将当前字节和上一个字节作为参数传入feed方法
                if i == 0:
                    self._last_char[1] = byte_str[0]
                    self.distribution_analyzer.feed(self._last_char, char_len)
                # 否则，将当前字节和上一个字节作为参数传入feed方法
                else:
                    self.distribution_analyzer.feed(byte_str[i - 1:i + 1],
                                                    char_len)

        # 将最后一个字节赋值给_last_char[0]
        self._last_char[0] = byte_str[-1]

        # 如果状态为DETECTING，则判断是否已经获取足够的数据，并且置信度是否大于SHORTCUT_THRESHOLD
        if self.state == ProbingState.DETECTING:
            if (self.distribution_analyzer.got_enough_data() and
                    (self.get_confidence() > self.SHORTCUT_THRESHOLD)):
                # 如果满足条件，则将状态设置为FOUND_IT
                self._state = ProbingState.FOUND_IT

        # 返回状态
        return self.state

    def get_confidence(self):
        # 获取置信度
        return self.distribution_analyzer.get_confidence()
