#!/usr/bin/python
# -*- coding: GBK -*-
#-------------------------------------------------------------------------------
#
#-------------------------------------------------------------------------------
#
##@package EventReport
#
# @todo:ʼþ»ã±¨
# @author hxp
# @date 2015-1-14
# @version 1.9
# @Note£º  EventReport_EventReportÓ÷¨ µÚÒ»¸ö²ÎÊý´«postÄÚÈÝurlencode£¬µÚ2,3,4²»Ó㻵ÚÎå¸ö²ÎÊý0´ú±íget£¬1Ϊpost£»µÚÁù¸ö²ÎÊýΪurl
#
# @change: "2015-01-28 22:30" hxp ¹Ø±Õʼþ»ã±¨
# @change: "2015-02-06 20:40" Alee ʼþ»ã±¨·¢ËÍÖÁºÏ·þÖ÷·þ
# @change: "2015-06-08 20:30" hxp Ôö¼ÓchannelCode
# @change: "2015-07-13 14:00" hxp Ôö¼ÓpidÐÅÏ¢
# @change: "2016-07-18 19:00" hxp 9377¶À´úʼþ»ã±¨°æ
# @change: "2016-07-27 20:00" Alee Ð޸Ĵò¿ªÎļþ³¬Ê±¹Ø±Õ
# @change: "2016-08-30 23:00" hxp ×Ô¶¨ÒåÔÚÏßÈËÊý; ÁÄÌì¼à¿Ø
# @change: "2016-09-10 11:00" hxp ÁÄÌìÄÚÈÝÌæ»»»»ÐÐ
# @change: "2017-07-01 15:30" hxp ƽ̨ÐÅÏ¢¸ÄΪ´ÓÍæ¼ÒÕ˺ÅÖÐÈ¡£¬Ö§³Ö»ì·þģʽ
# @change: "2017-07-04 15:00" hxp Ôö¼Ó»ì·þģʽÏ¿ÉÇø·Ö¸÷ƽ̨×ÔÉíÇø·þºÏ·þºóµÄƽ̨Ö÷·þID
# ÏêϸÃèÊö: ʼþ»ã±¨
#
#---------------------------------------------------------------------
#"""Version = 2017-07-04 15:00"""
#---------------------------------------------------------------------
import ReadChConfig
import ShareDefine
import GameWorld
import datetime
import random
import time
import md5
import os
import re
EventFilepath = "D:\\EventServer\\PythonScribe\\EventLog\\" 
g_wFileName = ""
g_writeHandle = None  # ²»¿ÉÖ±½Óµ÷ÓÃ
g_whStartTime = 0     # ´´½¨Îļþʱ¼ä
Def_WriteTime = 2   # Îļþ³ÖÐøÐ´Èëʱ¼ä£º·ÖÖÓ
def OnTimeCloseScribeTxt():
    global g_whStartTime
    global g_writeHandle
    global g_wFileName
    try:
        if g_whStartTime == 0:
            return
        
        #Îļþ´´½¨³¬¹ý
        if time.time() - g_whStartTime < 60*(Def_WriteTime + 1):
            return
        
        if g_writeHandle == None:
            return
        g_writeHandle.close()
        g_wFileName = ""
        g_whStartTime = 0
    except:
        GameWorld.ErrLog("OnTimeCloseScribeTxt ³ö´í")
## ³õʼ»¯Ê¼þ
#  @param None
#  @return ÎÞ·µ»ØÖµ
def InitDllAppID():
    appID = "mobile"
    key = "mobile"
    GameWorld.GetGameWorld().EventReport_SetEventReportParam(appID, key)
    GameWorld.Log("³õʼ»¯Ê¼þ±¨¸æ: appID=%s,key=%s OK!" % (appID, key))
    return
## ʼþ±¨¸æ¼Ç¼
#  @param eventActionID ʼþid
#  @param eventParam ʼþ²ÎÊý
#  @param curPlayer 
#  @return None
def EventReport(eventActionID, eventParam, curPlayer=None, OperatorID=""):
    # ×é³ÉÀý×Ó eventParam µÄ¸ñʽ±ØÐëÊÇ xx=yy&zz=cc
    #  "http://192.168.0.249:12000/event_receiver?EventID=3099&OperatorID=test&PlayerCount=102&Time=2018-02-08 18:30:30&ProductID=snxxz&RegionName=s1"
    if not curPlayer and not OperatorID:
        return
    ProductID = ReadChConfig.GetPyMongoConfig("EventReport", "ProductID")
    ReportUrl = ReadChConfig.GetPyMongoConfig("EventReport", "ReportUrl")
    RegionName = GameWorld.GetServerSID() # Ð迼ÂǺϷþÇé¿ö
    
    playerInfo = ""
    if curPlayer:
        playerInfo = "&AccountID=%s&IP=%s"%(GameWorld.GetPlatformAccID(curPlayer.GetAccID()),
                                                            curPlayer.GetIP())
        #=======================================================================
        # #UTF8 ÐèҪת³Éurl±àÂë²Å¿ÉÓÃ
        # playerInfo = urllib.urlencode({"RoleID": curPlayer.GetName(),
        #                  "AccountID": GameWorld.GetPlatformAccID(curPlayer.GetAccID()),
        #                  "IP": curPlayer.GetIP(),
        #                  "Level": curPlayer.GetLV()}) 
        #=======================================================================
        OperatorID = GameWorld.GetPlayerPlatform(curPlayer.GetAccID())
    
    getUrl = "%s?ProductID=%s&OperatorID=%s&RegionName=%s&EventID=%s%s&Time=%s&%s"%(\
             ReportUrl, ProductID, OperatorID, RegionName, eventActionID, playerInfo,
             str(datetime.datetime.today()).split('.')[0], eventParam)
    GameWorld.DebugLog("EventReport: %s"%getUrl)
    
    # µÚÎå¸ö²ÎÊý0´ú±íget·¢ËÍ  1´ú±ípost
    GameWorld.GetGameWorld().EventReport_EventReport("", "", "", "", 0, getUrl)
    return
## дʼþ±¨¸æÎļþ
#  @param eventClass 
#  @return None
def WriteEvent(eventClass):
    if GameWorld.IsMergeServer():
        return
    
    if eventClass.GetScribeEventName() not in ReadChConfig.GetEvalChConfig("EventReportID"):
        return
    
    try:
        if not os.path.isdir(EventFilepath):
            os.makedirs(EventFilepath)
        
        #³¢ÊÔдµ½Í¬Ò»¸öÎļþµ«ÊÇwindow »áÓÐbug£¬Ö»Äܸ÷×Ô³ÌÐò·Ö¿ªÐ´Èë
        fp_w = GetWriteIO()
        fp_w.write("%s\t%s\n"%(eventClass.GetScribeEventName(), eventClass.GetCurEventStr()))
        fp_w.flush()
    except:
        GameWorld.ErrLog("scribeʼþдÈë³ö´í¡£")
    return
# ·ÖÖÓ×¼µãУ׼
def FixTime():
    curTime = datetime.datetime.today()
    curTime = curTime + datetime.timedelta(minutes=Def_WriteTime-curTime.minute%Def_WriteTime)
    tmp = str(curTime).split(".")[0][:-3].replace(':', '-')
    return tmp.replace(" ", "_")
def GetLogFileName(fileStr):
    sessionid = md5.md5(str(random.random()) + str(time.time())).hexdigest()
    return EventFilepath + sessionid + fileStr + '.log'
def GetWriteIO():
    global g_wFileName
    global g_writeHandle
    global g_whStartTime
    
    fileTime = FixTime()
    if g_wFileName and fileTime in g_wFileName:
        #µ±Ç°ÎļþÖ±½Ó·µ»Ø
        return g_writeHandle
    curFileName = GetLogFileName(fileTime)
    if g_writeHandle != None:
        #¹Ø±Õ¾ÉÎļþ
        g_writeHandle.close()
    
    g_wFileName = curFileName
    g_writeHandle = open(g_wFileName, 'a+')
    g_whStartTime = time.time()
    return g_writeHandle
# ÿ¸ö×ֶζ¼Ó¦¸ÃתΪ×Ö·û´®£¬²»È»join»á±¨´í
class ScribeEvent(object):
    def __init__(self):
        #±ØÐë×Ö¶Î
        self.product_slug = 'yhlz'  # ÓÎÏ·±êÖ¾
        self.agent_name = ReadChConfig.GetPyMongoConfig("platform", "PlatformName") # ƽ̨±êÖ¾
        self.gameserver_no = ReadChConfig.GetPyMongoConfig("platform", "ServerID")[1:] # Çø·þ
        self.time = ""    #GameWorld.GetCurrentDataTimeStr()
        
    def SetEventAgentInfo(self, accIDPlatform):
        # ÉèÖôúÀíÔËÓªÉÌÐÅÏ¢
        # @param accIDPlatform: ÕâÀïÈ¡Õ˺ÅËùÊôƽ̨£¬Ö§³Ö»ì·þ, Èç¹ûÈ¡²»µ½£¬ÔòÓÃĬÈÏÅäÖõÄÔËÓªÉÌÐÅÏ¢
        if not accIDPlatform:
            return
        self.agent_name = accIDPlatform
        self.gameserver_no = str(GameWorld.GetPlayerMainServerID(self.agent_name))
        return
    
    #¼´Ê¹ÊǷDZØÐë×Ö¶ÎÒ²Ó¦¸Ã´«ËÍ£¬¸÷×Ö¶ÎÓÃ,·Ö¸ô£¬²¢ÇÒÓÃË«ÒýºÅ°üº¬£¬²Î¿¼¸ñʽ'"1","","","12314"'
    #±ÜÃâÐ޸ĸñʽµÄÇé¿ö£¬ÕâÀïͳһÐ޸ļ´¿É
    def GetEventStr(self, tmpList):
        return '\"%s\"'%'","'.join(tmpList)
    
# ÔÚÏßÈËÊý
class concurrency(ScribeEvent):
    def __init__(self):
        #±ØÐë×Ö¶Î
        super(concurrency, self).__init__()
        self.concurrency = 0   # ÔÚÏßÈËÊý
        #·Ç±ØÐë×Ö¶Î
        
        #¼´Ê±ÊǷDZØÐë×Ö¶ÎÒ²Ó¦¸Ã´«ËÍ£¬¸÷×Ö¶ÎÓÃ,·Ö¸ô£¬²¢ÇÒÓÃË«ÒýºÅ°üº¬£¬²Î¿¼¸ñʽ'"1","","","12314"'
    
    def GetCurEventStr(self):
        if not self.time:
            self.time = GameWorld.GetCurrentDataTimeStr()
        tmpList = [self.product_slug, self.agent_name, 
                   self.gameserver_no, self.time, str(self.concurrency)]
        
        return super(concurrency, self).GetEventStr(tmpList)
    
    def GetScribeEventName(self): return ShareDefine.Def_UserAction_KeepOnline
    
    
# 3.3.15. custom©\concurrency£¨Õû5·ÖÖÓ·Ö·þÇø×Ô¶¨ÒåÔÚÏßÍæ¼ÒÈËÊý£©
# ÓÃÓÚ×Ô¶¨ÒåÍæ¼ÒÔÚÏßÈËÊýÏà¹ØÍ³¼Æ£¬ÊÕ¼¯ÐèÒªµ¥¶Àͳ¼ÆµÄ×Ô¶¨ÒåÀàÐ͵ÄÔÚÏßÊý¾Ý¡£
class custom_concurrency(ScribeEvent):
    def __init__(self):
        #±ØÐë×Ö¶Î
        super(custom_concurrency, self).__init__()
        self.concurrency = 0   # ÔÚÏßÈËÊý
        self.type_name = ""   # ×Ô¶¨ÒåÀàÐÍ
        
        #·Ç±ØÐë×Ö¶Î
        
        #¼´Ê±ÊǷDZØÐë×Ö¶ÎÒ²Ó¦¸Ã´«ËÍ£¬¸÷×Ö¶ÎÓÃ,·Ö¸ô£¬²¢ÇÒÓÃË«ÒýºÅ°üº¬£¬²Î¿¼¸ñʽ'"1","","","12314"'
        return
    
    def GetCurEventStr(self):
        if not self.time:
            self.time = GameWorld.GetCurrentDataTimeStr()
        tmpList = [self.product_slug, self.agent_name, self.gameserver_no, self.time, str(self.concurrency), self.type_name]
        
        return super(custom_concurrency, self).GetEventStr(tmpList)
    
    def GetScribeEventName(self): return ShareDefine.Def_UserAction_CustomConcurrency
    
# 3.3.9. custom-events£¨×Ô¶¨Òåʼþ£©
# ÓÃÓÚͳ¼ÆÈÎºÎÆÚÍûÈ¥¸ú×ÙµÄÊý¾Ý
class custom_events(ScribeEvent):
    def __init__(self):
        #±ØÐë×Ö¶Î
        super(custom_events, self).__init__()
        self.account_id = "" # Õ˺ŠID£¬Æ½Ì¨ÏÂΨһ£¬ÇÒÖÕÉú²»±ä
        self.event_name = "" # ʼþÃû³Æ
        self.session_id = "" # ȇȡID
        
        #·Ç±ØÐë×Ö¶Î
        self.ip = "" # IP µØÖ·
        self.account_name = "" # Õ˺ŵǼÃû
        self.account_type = 0 # Õ˺ÅÀàÐÍ
        self.chr_name = "" # Íæ¼Ò½ÇÉ«Ãû
        self.chr_level = 0 # Íæ¼Ò½ÇÉ«µÈ¼¶
        self.comments = "" # ±¸×¢»ò¸½¼ÓÐÅÏ¢ char(255)
        #¼´Ê±ÊǷDZØÐë×Ö¶ÎÒ²Ó¦¸Ã´«ËÍ£¬¸÷×Ö¶ÎÓÃ,·Ö¸ô£¬²¢ÇÒÓÃË«ÒýºÅ°üº¬£¬²Î¿¼¸ñʽ'"1","","","12314"'
        return
    
    def GetCurEventStr(self):
        if not self.time:
            self.time = GameWorld.GetCurrentDataTimeStr()
        tmpList = [self.product_slug, self.agent_name, self.ip, self.gameserver_no, self.account_id, self.account_name, 
                   str(self.account_type), self.time, self.chr_name, str(self.chr_level), self.event_name,
                   self.comments, self.session_id]
        
        return super(custom_events, self).GetEventStr(tmpList)
    
    def GetScribeEventName(self): return ShareDefine.Def_UserAction_CustomEvents
    
# 3.3.13. chat-log £¨ÁÄÌìÏûÏ¢£©
# ÓÃÓÚ¼à¿ØÍæ¼ÒÁÄÌì
class chat_log(ScribeEvent):
    def __init__(self):
        #±ØÐë×Ö¶Î
        super(chat_log, self).__init__()
        self.account_id = "" # Õ˺ŠID£¬Æ½Ì¨ÏÂΨһ£¬ÇÒÖÕÉú²»±ä
        self.chr_name = "" # Íæ¼Ò½ÇÉ«Ãû
        self.content = "" # ÁÄÌìÄÚÈÝ
        self.cmc_name = "" # ÁÄÌìÆµµÀ±êʶ
        
        #·Ç±ØÐë×Ö¶Î
        self.ip = "" # IP µØÖ·
        self.account_name = "" # Õ˺ŵǼÃû
        self.account_type = 0 # Õ˺ÅÀàÐÍ
        self.chr_level = 0 # Íæ¼Ò½ÇÉ«µÈ¼¶
        self.object = "" # ˽ÁĶÔÏó
        self.addinfo = "" # ¶îÍâÐÅÏ¢
        #¼´Ê±ÊǷDZØÐë×Ö¶ÎÒ²Ó¦¸Ã´«ËÍ£¬¸÷×Ö¶ÎÓÃ,·Ö¸ô£¬²¢ÇÒÓÃË«ÒýºÅ°üº¬£¬²Î¿¼¸ñʽ'"1","","","12314"'
        return
    
    def GetCurEventStr(self):
        if not self.time:
            self.time = GameWorld.GetCurrentDataTimeStr()
        tmpList = [self.product_slug, self.agent_name, self.ip, self.gameserver_no, self.account_id, self.account_name, 
                   str(self.account_type), self.time, self.chr_name, str(self.chr_level), self.object, self.content,
                   self.addinfo, self.cmc_name]
        
        return super(chat_log, self).GetEventStr(tmpList)
    
    def GetScribeEventName(self): return ShareDefine.Def_UserAction_ChatLog
    
## =================================================================================================
## ÔÚÏß
def WriteEvent_concurrency(activePlayerCount, tjgOnlineCnt, OperatorID):
    # Ö»´«ÕæÊµÍæ¼Ò£¬Èúǫ́ÏÔÊ¾ÕæÊµÔÚÏßÍæ¼Ò
    realPlayer = activePlayerCount-tjgOnlineCnt
    EventReport(ShareDefine.Def_UserAction_KeepOnline, 
                "PlayerCount=%s&TotalPlayerCount=%s"%(realPlayer, realPlayer), None, OperatorID)
    return
## ×Ô¶¨ÒåÔÚÏß
def WriteEvent_custom_concurrency(platform, concurrency, type_name):
    customConcurrency = custom_concurrency()
    customConcurrency.SetEventAgentInfo(platform)
    customConcurrency.concurrency = concurrency
    customConcurrency.type_name = type_name
    WriteEvent(customConcurrency)
    return
def WriteEvent_chat_log(curPlayer, content, cmc_name, tagName="", addinfo=""):
    return
    '''
    @todo: дÁÄÌì¼à¿Ø¼Ç¼
    @param content: ÁÄÌìÄÚÈÝ
    @param cmc_name: ÁÄÌìÆµµÀ±êʶ
    @param tagName: ˽ÁĶÔÏó
    @param addinfo: ¶îÍâÐÅÏ¢
    '''
    
    chatlogEvent = chat_log()
    chatlogEvent.SetEventAgentInfo(GameWorld.GetPlayerPlatform(curPlayer.GetAccID()))
    chatlogEvent.account_id = GameWorld.GetPlatformAccID(curPlayer.GetAccID())
    chatlogEvent.chr_name = curPlayer.GetName()
    chatlogEvent.content = __GetEventChatContent(content)
    chatlogEvent.cmc_name = cmc_name
    chatlogEvent.ip = curPlayer.GetIP()
    chatlogEvent.account_name = chatlogEvent.account_id
    chatlogEvent.account_type = 0
    chatlogEvent.chr_level = 0
    chatlogEvent.object = tagName
    chatlogEvent.addinfo = addinfo
    WriteEvent(chatlogEvent)
    return
def __GetEventChatContent(content):
    '''
    [µØÍ¼:ĺ¹âÖ®³Ç(74,60)]
    [ÉñÊ¥µÄ°ÁÊÀÖ®¹ +40]
    '''
    tempMatch = re.search(".*?", content)
    if tempMatch:
        tempStr = tempMatch.group()
        markIndex = tempStr.index(">") + 1
        repStr = tempStr[markIndex:tempStr.index("<", markIndex)]
        content = content.replace(tempStr, repStr)
        
    tempMatch = re.search(".*?", content)
    if tempMatch:
        tempStr = tempMatch.group()
        markIndex = tempStr.index(">") + 1
        repStr = tempStr[markIndex:tempStr.index("<", markIndex)]
        content = content.replace(tempStr, repStr)
        
    # Ìæ»»»»ÐÐ
    content = content.replace("\r", "") 
    content = content.replace("\n", "") 
    return content