from Pycard import model, dialog
import wx
import wx.media
import platform
import sys
from skylive.utils import genutils as utils
#from skylive import streaming


class Stream(model.Background):

   volume = 2.5
   playinguri = ""

   def on_initialize(self, event):
      self.parent = self.getParent()
      self.playing = False
      self.replay = False
      if utils.platform() in ('Windows', 'Microsoft'):
         if int(sys.getwindowsversion()[0]) > 5:
            # XXX This is a temporary solution!
            self.components.StreamCombo.enabled=False
         if int(sys.getwindowsversion()[0]) < 5:
            self.mc = wx.media.MediaCtrl(self.components.Video)
         else:
            self.mc = wx.media.MediaCtrl(self.components.Video, szBackend=wx.media.MEDIABACKEND_WMP10)
      else:
         self.mc = wx.media.MediaCtrl(self.components.Video)



      self.video_sizer = wx.BoxSizer(wx.VERTICAL)
      self.video_sizer.Add(self.mc,5, wx.EXPAND|wx.ALL, border=10)
      self.components.Video.SetSizer(self.video_sizer)
      
      wx.CallAfter(self.on_Play_mouseClick)

   def on_Slider1_select(self, event):
      vol = self.components.Slider1.value
      self.volume = float((50.0-vol)/10)
      #print float(self.volume), vol
      self.mc.SetVolume(float(self.volume))

   def getStream(self):
      StreamUri=self.parent.StreamUri.split(";")
      idx=1
      self.components.StreamCombo.items=[]
      for u in StreamUri:
         self.components.StreamCombo.append('stream'+str(idx))
         idx=idx+1
      streamidx=int(self.parent.streamingIndex)
      try:
         stream = StreamUri[streamidx]
      except:
         stream = StreamUri[0]
      self.components.StreamCombo.text = self.components.StreamCombo.items[streamidx]
      if stream=='NONE':
         self.close()
      else:
         #if utils.platform() == 'Darwin':
         #   # XXX TODO QuickTime is very crappy. We really need to use GSTREAMER on
         #   # another way on OSX!
         #   if stream.startswith('http://') and (stream.endswith(':8000/skylive.ogg') or stream.endswith(':8000/skylive.mp3')):
         #      stream = stream.replace("http://", "icy://")[:-3]+'mp3'
         return stream


   def on_StreamCombo_textUpdate(self, event):
      stream = self.components.StreamCombo.text
      if not stream in self.components.StreamCombo.items:
         stream = self.components.StreamCombo.items[0]
         self.components.StreamCombo.text = stream
      idx=int(stream[-1])-1
      if int(self.parent.streamingIndex) != idx:
         self.parent.streamingIndex = idx
         self.parent.on_setStreamIdx(idx)
         if self.playing:
            self.stop()
            wx.CallAfter(self.on_Play_mouseClick)  


   def play(self, uri=False):
      if uri:
         self.playinguri = uri
         self.on_playAudioStream(uri)
      else:
         self.close(True)

   def stop(self):
      self.on_stopAudioStream()



   def changeStream(self, uri):
      if uri != self.playinguri:
         self.stop()
         self.replay=uri

   def on_playAudioStream(self, uri):
      #if not self.playing:
      #   self.components.Play.enable=False
      print 'PLAYAUDIOSTREAM'
      self.Bind(wx.media.EVT_MEDIA_LOADED, self.onMediaLoaded)
      self.Bind(wx.media.EVT_MEDIA_FINISHED, self.onMediaFinished)
      self.Bind(wx.media.EVT_MEDIA_PAUSE, self.onMediaPause)
      self.Bind(wx.media.EVT_MEDIA_PLAY, self.onMediaPlay)
      self.Bind(wx.media.EVT_MEDIA_STATECHANGED, self.onMediaStatechanged)
      self.Bind(wx.media.EVT_MEDIA_STOP,  self.onMediaStop)

      proxy=self.parent.config.get_usrProxy()
      if str(proxy['useProxy']).lower() in ['si', 'yes', 'true', True, 1]:
         p = int(proxy['proxyPort'])
         h = proxy['proxyUrl']
         pxy="http://"+str(h)+":"+str(p)
         if str(proxy['proxyAuth']).lower() in ['si', 'yes', 'true', True, 1]:
            usr = proxy['proxyUsrName']
            pwd = proxy['proxyUsrPsw']
            pxy="http://"+str(usr)+":"+str(pwd)+"@"+str(h)+":"+str(p)
         self.mc.LoadFromURI(uri, pxy)
      else:
         self.mc.LoadFromURI(uri)
      #self.mc.LoadFromURI(uri)
      self.components.Play.SetLabel("Loading")


   def onMediaFinished(self, event):
      print 'onMediaFinished'
      event.Skip()      

   def onMediaPause(self, event):
      print 'onMediaPause'
      event.Skip()

   def onMediaPlay(self, event):
      print 'onMediaPlay'
      event.Skip()

   def onMediaStatechanged(self, event):
      print 'onMediaStatechanged'
      event.Skip()

   def onMediaStop(self, event):
      if self.replay:
         self.play(self.replay)
         self.replay=False
      print 'onMediaStop'
      event.Skip()


   def onMediaLoaded(self, evt):
      print 'onMediaLoaded'
      #self.components.Play.enable=True
      self.components.Play.SetLabel("Stop")
      self.playing=True
      self.mc.Play()

   def on_stopAudioStream(self):
      self.mc.Stop()
      self.playing = False
      self.components.Play.SetLabel("Play")

   def stop(self):
      self.on_stopAudioStream()

   def on_close(self, event):
      try:
         self.stop()
      except:
         pass
      self.parent.on_CloseStream(event)
      event.skip()

   def on_exit_command(self, event):
      self.close()

   def on_size(self, event):
      self.panel.SetSize(self.size)

   def on_Play_mouseClick(self, event=False):
      if self.playing:
         self.on_stopAudioStream()
      else:
         # Why we need to start the stream 2 times? fucking windows...
         print 'PLAY'
         self.play(self.getStream())



