module GUI where

import Tetrispy (spy)
import Network
import Control.Concurrent
import Graphics.UI.Gtk

mainTetrispyGUI = do

    initGUI

    window <- windowNew
    window `onDestroy` mainQuit
    set window [ containerBorderWidth := 10 ]

    tableLayout <- tableNew 3 8 False

    portEntry <- entryNew
    entrySetText portEntry "5678"
    portLabel <- labelNew Nothing
    labelSetLabel portLabel "Port:"

    targetEntry <- entryNew
    entrySetText targetEntry "localhost"
    targetLabel <- labelNew Nothing
    labelSetLabel targetLabel "Target host:"

    targetPortEntry <- entryNew
    entrySetText targetPortEntry "6789"
    targetPortLabel <- labelNew Nothing
    labelSetLabel targetPortLabel "Target Port:"

    startButton <- buttonNew
    set startButton [ buttonLabel := "Start" ]
    onClicked startButton $ startSpy portEntry targetEntry targetPortEntry

    tableAttachDefaults tableLayout targetLabel     0 2   0 1
    tableAttachDefaults tableLayout targetEntry     2 8   0 1

    tableAttachDefaults tableLayout portLabel       0 1   1 2
    tableAttachDefaults tableLayout portEntry       1 4   1 2

    tableAttachDefaults tableLayout targetPortLabel 4 5   1 2
    tableAttachDefaults tableLayout targetPortEntry 5 8   1 2

    tableAttachDefaults tableLayout startButton     0 8   2 3
    
    tableSetRowSpacings tableLayout 5
    tableSetColSpacings tableLayout 5

    set window [ containerChild := tableLayout ]

    widgetShowAll window
    mainGUI

startSpy pE tE tPE = do
    port <- entryGetText pE
    portTarget <- entryGetText tPE
    target <- entryGetText tE

    forkOS $ spy (getPort port) target (getPort portTarget)
    putStrLn $ "Started with local port "++port++" forwarded to " ++ target++":"++portTarget

getPort :: String -> PortID
getPort s = PortNumber (fromInteger $ read s)

