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

import os
import sys

import wx
import wx.lib.newevent
import socket, select

import traceback

from module_msg import ModuleMsg
from cmd_controller import CmdController, CmdMsg
from gobang import Gobang, Stone

cur_dir = os.path.split(os.path.realpath(__file__))[0]

CountTimeEvent, EVT_COUNT_TIME = wx.lib.newevent.NewEvent()
PutStoneEvent, EVT_PUT_STONE = wx.lib.newevent.NewEvent()

class GuiPanel(wx.Panel):
    FACTOR = 24.0
    GRID_SIZE = 24

    #初始化，主要是控件的设置
    def __init__(self, parent, cmd_controller):
        self.frame = parent

        self.digit_bmps = None
        self.robot_radio = None
        self.network_radio = None
        self.ip_static_text = None
        self.ip_addr = None
        self.port_static_text = None
        self.port = None
        self.listen_btn = None
        self.connect_btn = None
        self.start_btn = None
        self.stop_btn = None
        self.status_static = None
        self.list_ctrl = None

        self.cmd_controller = cmd_controller
        self.cmd_controller.set_thread_func(self.work_thread)

        self.InitCtrl(parent)
        self.InitEvent()

    def InitCtrl(self, parent):
        wx.Panel.__init__(self, parent=parent)

        self.robot_radio = wx.RadioButton( self, wx.ID_ANY, "robot", (390, 100), (80, 30), 0 )
        self.Bind(wx.EVT_RADIOBUTTON, self.OnRobotRadio, self.robot_radio)

        self.network_radio = wx.RadioButton( self, wx.ID_ANY, "network", (530, 100), (80, 30), 0 )
        self.Bind(wx.EVT_RADIOBUTTON, self.OnNetworkRadio, self.network_radio)

        self.ip_static_text = wx.StaticText(self, -1, "ip:", pos = (390, 150), size = (15, 30), style = wx.ALL)
        self.ip_addr = wx.TextCtrl(self, -1, "127.0.0.1", (420, 150), (80, 30), style = wx.ALL)

        self.port_static_text = wx.StaticText(self, -1, "port:", pos = (510, 150), size = (30, 30), style = wx.ALL)
        self.port = wx.TextCtrl(self, -1, "8889", (550, 150), (50, 30), style = wx.ALL)

        self.listen_btn = wx.Button( self, wx.ID_ANY, "Listen", (390, 200), (100, 30), 0)
        self.connect_btn = wx.Button( self, wx.ID_ANY, "Connect", (500, 200), (100, 30), 0)

        self.start_btn = wx.Button(self, wx.ID_ANY, "start game", (390, 250), (100, 30), 0)
        self.stop_btn = wx.Button(self, wx.ID_ANY, "stop game", (500, 250), (100, 30), 0)

        self.status_static = wx.StaticText(self, -1, "", (390, 300), (200, 60), 0)

        self.digit_bmps = self.GetDigitBitmap()

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        self.count_time_event = None
        self.evt_count_time = None

        self.list_static = wx.StaticText(self, -1, "排行：", (10, 390), (100, 60), 0)

        self.list_ctrl = wx.ListCtrl(self, pos = (10, 420), size=(400,150), style=wx.LC_REPORT | wx.BORDER_SUNKEN)
        self.list_ctrl.InsertColumn(0, '昵称')
        self.list_ctrl.InsertColumn(1, '胜利次数', width = 125)
        self.list_ctrl.InsertColumn(2, '失败次数', width = 125)

        self.RefreshList()

        wx.PostEvent(self.robot_radio, wx.PyCommandEvent(wx.EVT_RADIOBUTTON.typeId, self.robot_radio.GetId()))


    #初始化事件
    def InitEvent(self):
        self.Bind(wx.EVT_BUTTON, self.OnListen, self.listen_btn)
        self.Bind(wx.EVT_BUTTON, self.OnConnect, self.connect_btn)

        self.Bind(wx.EVT_BUTTON, self.OnStart, self.start_btn)
        self.Bind(wx.EVT_BUTTON, self.OnStop, self.stop_btn)

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnStoneDown)


        self
.Bind(EVT_COUNT_TIME, self.OnPaintTime)
        self.Bind(EVT_PUT_STONE, self.OnPaintStone)

    #点击选项robot后初始化
    def InitSelectRobot(self):
        print "Init Select Robot"

        self.ip_addr.Show(False)
        self.ip_static_text.Show(False)

        self.port.Show(False)
        self.port_static_text.Show(False)

        self.listen_btn.Show(False)
        self.connect_btn.Show(False)

        print "2:start btn True"
        self.start_btn.Enable(True)
        print "3: stop btn False"
        self.stop_btn.Enable(False)

    #点击选项network后控件初始化
    def InitSelectNetwork(self):
        print "Init Select Network"
        self.ip_addr.Show(True)
        self.ip_static_text.Show(True)

        self.port.Show(True)
        self.port_static_text.Show(True)

        self.listen_btn.Show(True)
        self.connect_btn.Show(True)

        print "3:start btn False"
        self.start_btn.Enable(False)
        print "4: stop btn False"
        self.stop_btn.Enable(False)

    #点击start按钮后控件初始化
    def InitStartCtrl(self):
        self.robot_radio.Enable(False)
        self.network_radio.Enable(False)

        self.ip_addr.Enable(False)
        self.port.Enable(False)

        self.listen_btn.Enable(False)
        self.connect_btn.Enable(False)

        print "4:start btn False"
        self.start_btn.Enable(False)
        print "5: stop btn True"
        self.stop_btn.Enable(True)

    #点击stop按钮后控件初始化
    def InitStopCtrl(self):
        self.robot_radio.Enable(True)
        self.network_radio.Enable(True)

        self.ip_addr.Enable(True)
        self.port.Enable(True)

        self.listen_btn.Enable(True)
        self.connect_btn.Enable(True)


        if CmdController.NETPLAY_MODE == self.cmd_controller.mode:
            print "1:start btn False"
            self.start_btn.Enable(False)
            print "1:start btn True"
        elif CmdController.ROBOTPLAY_MODE == self.cmd_controller.mode:
            self.start_btn.Enable(True)

        print "1: stop btn false"
        self.stop_btn.Enable(False)

        # if self.cmd_controller.is_starting():
        wx.PostEvent(self, wx.PyCommandEvent(wx.wxEVT_ERASE_BACKGROUND))
        wx.PostEvent(self.GetEventHandler(), CountTimeEvent())


    #点击listen或者connect按钮之后，控件初始化
    def InitListenOrConnectCtrl(self):
        self.robot_radio.Enable(False)
        self.network_radio.Enable(False)

        self.ip_addr.Enable(False)
        self.port.Enable(False)

        self.listen_btn.Enable(False)
        self.connect_btn.Enable(False)

        self.start_btn.Enable(True)
        print "2: stop_btn True"
        self.stop_btn.Enable(True)


    def InsertItem(self, nickname, pos):
        pos = self.list_ctrl.InsertStringItem(0, nickname)

    def RefreshList(self):
        print "Refresh List"
        top_users = self.cmd_controller.get_top_users()
        wx.CallAfter(self.list_ctrl.DeleteAllItems)
        # self.list_ctrl.DeleteAllItems()
        pos = 0
        for user in top_users:
            wx.CallAfter(self.list_ctrl.InsertStringItem, pos, user.nickname)
            wx.CallAfter(self.list_ctrl.SetStringItem, pos, 1, str(user.win_times))
            wx.CallAfter(self.list_ctrl.SetStringItem, pos, 2, str(user.fail_times))
            # pos = self.list_ctrl.InsertStringItem(0, user.nickname)
            # self.list_ctrl.SetStringItem(pos, 1, str(user.win_times))
            # self.list_ctrl.SetStringItem(pos, 2, str(user.fail_times))

    #获取数字bitmap
    def GetDigitBitmap(self):
        digit_order = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
        digit_bmps = []

        bmp = wx.Bitmap("%s/res/digit.bmp" %(cur_dir))
        bmp_height = bmp.Height / 12
        bmp_width = bmp.Width
        for seq in digit_order:
            digit_bmps.append(bmp.GetSubBitmap(wx.Rect(0, bmp_height * seq, bmp_width, bmp_height)))
        return digit_bmps


    #根据点击的像素坐标转化为x,y格子坐标
    def GetGridOrient(self, x, y):
        x_grid = int(round(x / GuiPanel.FACTOR))
        y_grid = int(round(y / GuiPanel.FACTOR))

        x_grid -= 1
        y_grid -= 1

        if 0 <= x_grid < Gobang.GRIDS and  0 <= y_grid < Gobang.GRIDS:
            return (x_grid, y_grid)
        return (None, None)


    #处理关闭消息
    def OnClose(self, evt):
        print "OnClose"
        self.cmd_controller.exit_without_promt(CmdMsg("exit"))
        # if True == self.cmd_controller.is_starting():
        #     print "before tip"
        #     dlg = wx.MessageDialog(None, "您正处于游戏中, 是否要离开", '提示', wx.YES_NO | wx.ICON_INFORMATION)
        #     print "After tip"
        #     if dlg.ShowModa