"""
     Copyright (C) 2007-2009 Franco Lanza <nextime@nexlab.it>
     Copyright (C) 2007-2009 Sandro Aliano <ita595@hotmail.com>
     Copyright (C) 2007-2009 Ivan Bellia <skylive@skylive.it>

     Web site: http://www.astronomix.org/trac/Skylive-NG

     This file is part of Skylive-NG.

     Skylive-NG is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation, either version 3 of the License, or
     (at your option) any later version.

     Skylive-NG 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 General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with Skylive-NG.  If not, see <http://www.gnu.org/licenses/>.
"""

from Pycard import model, dialog, timer
import os, wx, webbrowser
from skylive import config
from skylive.utils import genutils
import time
from skylive import chatparser as parser

class ChatPrivate(model.Background):

   chathtml = []
   latest = ''

   def on_initialize(self, event):
      self.parent = self.getParent()
      if self.parent.lang == "it":
         self.blinkMsg = "Nuovo messaggio"
      else:
         self.blinkMsg = "New message"
      self.deactiv = False
      self.canSelect = False
      self.canbeep, self.canpopup = config.get_pvtPref()
      self.components.ChatMsg.setFocus()
      if genutils.platform() == 'Darwin':
         self.blinkTimer = timer.Timer(self.components.ChatArea, -1)
      self.origTitle = self.title
      self.iconOn = True
      self.last_idle = time.time()
      self.SetSizeHints(200, 200)
      self.resizeAll()

   def on_close(self, event):
      self.parent.on_PrivChatClose(self.touser)
      event.skip()

   def on_exit_command(self, event):
      self.close()
   
   def on_menuSavePrivChat_select(self, event):
      #self.chatPrivText = self.components.ChatArea.text
      self.chatPrivText = self.components.ChatArea.text
      self.chat_file_path = os.path.expanduser("~")
      self.chat_file_save_path = os.path.normpath(self.chat_file_path+"/skylive-ng_chat")
      self.usr_file_name = self.tousercomp+".txt"
      result = dialog.saveFileDialog(self, "Save Text file as:", self.chat_file_save_path, self.usr_file_name, 'Text Files: (*.txt)|*.txt')
      if result.accepted:
         self.path = result.paths[0]
         self.chat_file = open(self.path,"w")
         self.chat_file.write("Start private chat text whit "+self.tousercomp+"\n"+self.chatPrivText)
         self.chat_file.close()
         dialog.alertDialog(self, "Private chat text saved in "+self.path)
   
   def on_Send_mouseClick(self, event):
      txt = self.components.ChatMsg.text
      self.components.ChatMsg.text = ''
      if len(txt.replace(" ", "")) > 0:
         #self.components.ChatArea.appendText("<"+self.parent.config.getUsername()+"> "+txt+"\n")
         self.parent.addToPrivChatWindow(self.parent.config.getUsername(), parser.toHtml(txt), str(self.touser), 'red')
         #self.parent.callInTwisted('sendNetworkData', self.parent.srvproto.chatSendPrivate(self.tousercomp, txt))
         self.parent.TwistedLoop.sendNetworkData(self.parent.srvproto.chatSendPrivate(self.tousercomp, txt))

   def on_ChatMsg_keyPress(self, event):
      if event.GetKeyCode() == wx.WXK_RETURN:
         self.on_Send_mouseClick(event)
         event.skip()
      else:
         event.skip()

   def on_ChatArea_gainFocus(self, event):
      # Ugly, bad, orrible hack to make
      # the fucking windows work with RETURN keypress.
      if not self.canSelect:
         if os.name == 'nt':
            if len(self.components.ChatMsg.text) > 0:
               self.on_Send_mouseClick(False)
         event.skip()
         self.components.ChatMsg.setFocus()
   
   def on_deactivate(self, event):
      self.deactiv = True
   
   def on_activate(self, event):
      self.deactiv = False
      #self.components.ChatMsg.setFocus()
      if genutils.platform() == 'Darwin':
         self.blinkTimer.Stop()
      self.title = self.origTitle
   
   def on_ChatArea_textUpdate(self, event):
      print 'PrivChatArea Updated'
      if self.canbeep and self.deactiv:
         print '\a'
      if self.canpopup and self.deactiv:
         self.Restore()
      if True and self.deactiv:
         if genutils.platform() == 'Darwin':
            self.blinkTimer.Start(1000)
         else:
            self.RequestUserAttention()
   
   def on_ChatArea_mouseDown(self, event):
      self.canSelect = True
      event.skip()

   def on_ChatArea_mouseUp(self, event):
      self.canSelect = False
      event.skip()
   
   #def on_ChatArea_mouseDoubleClick(self, event):
   #   x = ''
   #   y = ''
   #   url = False
   #   posA = 0
   #   posB = 0
   #   noUrl = False
   #   cpoint = self.components.ChatArea.getSelection()
   #   while 'http' not in x and '>' not in x:
   #      x = self.components.ChatArea.getString(cpoint[0]-posA, cpoint[0]-posA+4)
   #      if '>' in x or '<' in x:
   #         noUrl = True
   #      posA+=1
   #   if not noUrl:
   #      while y != ' ' and y != '\n':
   #         y = self.components.ChatArea.getString(cpoint[1]+posB, cpoint[1]+posB+1)
   #         posB+=1
   #      A = cpoint[0]-posA+1
   #      B = cpoint[1]+posB-1
   #      text = self.components.ChatArea.getString(A, B)
   #      if len(text.split(' ')) > 1:
   #         urlTry = text.split(' ')[0]
   #      else:
   #         urlTry = text
   #      if len(urlTry) > 12:
   #         url = urlTry
   #   try:
   #      if url:
   #         webbrowser.open(url)
   #   except:
   #      self.dialog.alertdialog(self, "Default WebBrowser is not defined")

   def on_ChatArea_keyPress(self, event):
      key = event.GetKeyCode()
      if key in range (31, 128):
         self.components.ChatMsg.setFocus()
         self.components.ChatMsg.appendText(unicode(chr(key)))
      else:
         self.components.ChatMsg.setFocus()
      event.skip()

   def on_ChatArea_timer(self, event):
      if self.iconOn:
         self.title = self.blinkMsg
         self.iconOn = False
      else:
         self.iconOn = True
         self.title = self.origTitle
      event.skip()
 
   def on_size(self, event):
      w, h = self.size
      if w >= 200 and h >= 200:
         self.resizeAll()      

   def resizeAll(self):
      winW, winH = self.size
      areaW=winW-26
      areaH=winH-97
      self.components.ChatArea.size = (areaW, areaH)
      inputW = areaW-78
      inputH = 27
      self.components.ChatMsg.size = (inputW, inputH)
      self.components.ChatMsg.position = (10, areaH+13)
      self.components.Send.position = (inputW+15, areaH+15)
      self.panel.SetSize(self.size)

