import wx 
import wx.html2 
import keyboard
import mouse
import time
import os,sys

path = os.getcwd()
MY_BOOK = path + "/mybook."

actWinSW    = True
tBarSW      = True
mybook      = {}
mybookTtl   = {}
keyList = [ "f1","f2","f3","f4","f5","f6","f7","f8","f9","f10" ]



def dbg( s ):
    return
    
    home_path = os.getenv('HOMEPATH')
    fp=open( home_path + "/dbg.txt" , "a")
    fp.write( s+ "\n" )
    fp.close()


# //sys.exit()

headStr="""
<H2>YouTube登録リスト</H2>
<hr><pre>
<h3>
[Esc]は、この画面を表示します
[Esc+Shift]は、<a href="https://www.youtube.com">YouTube</a>へ
</h3></pre>
<hr>
"""
helpStr="""
<hr>
<pre>
画面表示は、<b>ファンクションを押すかリンク先</b>をクリックして下さい！

登録は、<b>F1 + Alt</b>など
Altキーを押しながらファンクションキーを押します。
登録されると、YouTue登録リスト(この画面)が表示されます。


マウスポインターをウインドウ内に移動すると、
タイトルバーが表示されて<b>ウインドウの移動、リサイズ、最小化、終了</b>ができます。

ウインドウの外側ではタイトルバーが消えますので、
<b>YouTube画面で全画面</b>にしておけば<b>ウインドウ全体</b>で見ることができます。


タイトルが無い所は未登録で、登録済みのファンクションは上書きされます。
</pre>
"""

st = os.path.exists( MY_BOOK + "txt" )
if not st:
    fp=open( MY_BOOK + "txt" , "w")
    fp.close()
    dbg("nasi"+ MY_BOOK + "txt" );
else:
    dbg("ari"+ MY_BOOK + "txt" );

st = os.path.exists( MY_BOOK + "html" )
if not st:
    fp=open( MY_BOOK + "html" , "w")
  
    s="""
<pre>
[F01]
[F02]
[F03]
[F04]
[F05]
[F06]
[F07]
[F08]
[F09]
[F10]
</pre>
    """
    fp.write( headStr )
    fp.write( s )
    fp.write( helpStr )
    fp.close()
    dbg("nasi"+ MY_BOOK + "html" );
else:
    dbg("ari"+ MY_BOOK + "html" );
    
    
# //class MyBrowser(wx.Dialog): 
class MyBrowser(wx.Frame): 
    
    def __init__(self, *args, **kwds): 
        wx.Frame.__init__(self, *args, **kwds) 
            # //style=(
               # //wx.DEFAULT_FRAME_STYLE|  wx.RESIZE_BORDER | wx.CLOSE_BOX | wx.CAPTION | wx.ICONIZE | wx.MAXIMIZE | wx.STAY_ON_TOP ))
                # //wx.RESIZE_BORDER | wx.FRAME_NO_TASKBAR  ))

        self.browser = wx.html2.WebView.New(self) 
        
        sizer = wx.BoxSizer(wx.VERTICAL) 
        sizer.Add(self.browser, 1, wx.EXPAND, 10) 
        self.SetSizer(sizer) 
        self.SetSize((900, 500)) 



# //-------------------------------------------------------
# //   
# //-------------------------------------------------------
def readFile():
    
    fp =open( MY_BOOK + "txt" )

    data = fp.read()
    fp.close()
    
    dataList = data.split("\n")
    
    for line in dataList:
        if line == "":
            break
            
        s = line.split(":")
        #print( "line=", line  )
        #print( "s=", s  )
        ky = s[0]
        bdy= s[1]
        ttl= s[2]
        mybook[ ky ]    = bdy
        mybookTtl[ ky ] = ttl

    #print( "mybook=", mybook)
    
def wrtFile():

    global mybook
            
    fp =open(   MY_BOOK + "txt",    "w" )
    fp2 =open( MY_BOOK + "html",    "w" )
    
    
    fp2.write( headStr )
    
    
    for i in range(1, 10+1):
        #print(i)
        
        key = "f%d" %i
        if key in mybook:
        
            s = "%s:%s:%s\n" %( key, mybook[key], mybookTtl[key]  )
            #print( "s=",s )
            fp.write(s)

            s2 = "[F%02d]　<a href='https://%s'>%s</a><br>\n" %( i, mybook[key], mybookTtl[key]  )
            #print( "s2=",s2 )
            fp2.write(s2)
        else:
            s2 = "[F%02d]　<a href='https://%s'>%s</a><br>\n" %( i, "", ""  )
            #print( "s2=",s2 )
            fp2.write(s2)

    fp2.write(helpStr)
        
    fp.close()
    fp2.close()
    

# //-------------------------------------------------------
# //    キーボードイベント
# //-------------------------------------------------------
def keyCallback( event ):

    global dialog, mybook, mybookTtl, actWinSW
    
    #print( event )
    #print( keyboard.is_pressed('alt'))

    if not tBarSW:
        return
        
        
    if "up" == event.event_type:
        if "left" == event.name:
            dialog.browser.GoBack()
            return
        if "right" == event.name:
            dialog.browser.GoForward()
            return
            
        if "esc" == event.name:
            if keyboard.is_pressed('shift'):
                dialog.browser.LoadURL("https://www.youtube.com/") 
            else:
                dialog.browser.LoadURL( "file:///%shtml" %( MY_BOOK ) ) 
            return
            
        elif event.name in keyList:
            if  keyboard.is_pressed('alt'):
                url =dialog.browser.GetCurrentURL()
                ttl =dialog.browser.GetCurrentTitle()
                url = url.replace( "https://","")
                url = url.replace( "http://", "")
                # //url = url.replace("www.youtube.com/watch?v=", "www.youtube.com/embed/")
                #print( "(FN)url", url)
                mybook[ event.name ] = url
                mybookTtl[ event.name ] = ttl
                #print( "mybook=", mybook)
                wrtFile()
                time.sleep(1)
                dialog.browser.LoadURL( "file:///%shtml" %( MY_BOOK ) ) 
            else:
                key = event.name
                readFile()              # ブックマークの読み込み
                if key in mybook:
                    dialog.browser.LoadURL( mybook[ key  ] ) 
     
            actWinSW= False


# //-------------------------------------------------------
# //マウスのイベント
# //-------------------------------------------------------
def mouseCallback( event ):

    global dialog, actWinSW, tBarSW

    # //print('mouseCallback-Event:', event )
    # //print('mouseCallback-Event:', type(event) == mouse.ButtonEvent      )

    actWinSW = False
    if type(event) == mouse.MoveEvent:

        pos = dialog.GetScreenPosition()
        sz  = dialog.GetSize()
        x1 = pos.x
        y1 = pos.y
        x2 = pos.x + sz.width
        y2 = pos.y + sz.height
        x0 = event.x
        y0 = event.y
        
        if (x0 > x1 and x0 < x2): 
            if (y0 > y1 and y0 < y2):
                # //print("OK")
                actWinSW = True
                 
        if tBarSW:
            # タイトルバーは表示中
            if actWinSW:
                pass
            else:
                #タイトルバーを消す
                tBarSW = False
                dialog.SetWindowStyle( wx.FRAME_NO_TASKBAR | wx.RESIZE_BORDER ) 
        else:
            # タイトルバーは表示されていない！
            if actWinSW:
                # タイトルバーを表示させる
                tBarSW = True
                dialog.SetWindowStyle( wx.DEFAULT_FRAME_STYLE ) 
            else:
                pass

            
    if type(event) == mouse.ButtonEvent:
        if event.event_type == "up" and event.button=="left":
            pass

   

if __name__ == '__main__': 

    readFile()              # ブックマークの読み込み
    app = wx.App() 
    dialog = MyBrowser(None, -1) 
    # //dialog.browser.LoadURL("https://www.youtube.com") 
    dialog.browser.LoadURL( "file:///%shtml" %( MY_BOOK ) ) 
    # //dialog.browser.LoadURL("https://youtu.be/c4AIZcmb23s") 
    # //dialog.browser.LoadURL("https://www.youtube.com/watch?v=86LY7h7xoIA") 
    data ="""
    <html>
    <body>
    <iframe width="1436" height="833" src="https://www.youtube.com/embed/c4AIZcmb23s" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    </body>
    </html>

    """
    # //dialog.browser.SetPage( data, "" )

    keyboard.hook( keyCallback )
    mouse.hook( mouseCallback )
    dialog.Show() 
    dialog.Maximize(False)
    app.MainLoop() 

