
--[[
=head1 NAME

applets.JogglerNetwork.JogglerNetworkApplet

=head1 DESCRIPTION

JogglerNetwork v1.03 (25th April 2012)

This applet is used to choose between wired or wireless interfaces on the Joggler and triggers configuration scripts.

=cut
--]]


-- stuff we use
local setmetatable, tonumber, tostring = setmetatable, tonumber, tostring

local os                     = require("os")
local io                     = require("io")
local oo                     = require("loop.simple")
local math                   = require("math")
local string                 = require("string")
local table                  = require("jive.utils.table")
local debug                  = require("jive.utils.debug")

local Applet                 = require("jive.Applet")
local System                 = require("jive.System")
local Checkbox               = require("jive.ui.Checkbox")
local Choice                 = require("jive.ui.Choice")
local Framework              = require("jive.ui.Framework")
local Event                  = require("jive.ui.Event")
local Icon                   = require("jive.ui.Icon")
local Label                  = require("jive.ui.Label")
local Button                 = require("jive.ui.Button")
local Popup                  = require("jive.ui.Popup")
local Group                  = require("jive.ui.Group")
local RadioButton            = require("jive.ui.RadioButton")
local RadioGroup             = require("jive.ui.RadioGroup")
local SimpleMenu             = require("jive.ui.SimpleMenu")
local Slider                 = require("jive.ui.Slider")
local Surface                = require("jive.ui.Surface")
local Textarea               = require("jive.ui.Textarea")
local Textinput              = require("jive.ui.Textinput")
local Window                 = require("jive.ui.Window")
local ContextMenuWindow      = require("jive.ui.ContextMenuWindow")
local Timer                  = require("jive.ui.Timer")
local Keyboard               = require("jive.ui.Keyboard")

local appletManager = appletManager

local jiveMain		= jiveMain


module(..., Framework.constants)
oo.class(_M, Applet)

-- Define the standard menu.
function setupJogglerNetwork(self, menuItem)

	self:storeSettings()

	local group = RadioGroup()
	
	local nic = self:getSettings()["nic"]
	log:info(nic)

	local window = Window("text_list", self:string("NETWORK"))

	ipaddr = os.capture('sqp_JogglerNetwork.sh ip')
	headermsg = Textarea("help_text", ipaddr)

	menu = SimpleMenu("menu",
		{
		
			{
				text = self:string("WIREDCHOICE"),
				style = 'item_choice',
				check = RadioButton(
					"radio",
					group,
					function()
						self:getSettings()["nic"] = "eth0"
					end,
					(nic == "eth0")
				),
			},
			{
				text = self:string("WIRELCHOICE"),
				style = 'item_choice',
				check = RadioButton(
					"radio",
					group,
					function()
						self:getSettings()["nic"] = "wlan0"
					end,
					(nic == "wlan0")
				),
			},
			{
				text = self:string("WIRELSSID"),
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					self:ssidkeyWindow(menuItem, 'qwerty', Textinput.textValue("", 1, 99))					
				end
			},
			{
				text = self:string("WIRELPASS"),
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					self:passkeyWindow(menuItem, 'qwerty', Textinput.textValue("", 8, 99))					
				end
			},
			{
				text = self:string("NETRESET"),
				style = 'item_choice',
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					self:storeSettings()
					os.execute("sqp_JogglerNetwork.sh reset")
					self:getSettings()["nic"] = "eth0"
					self:getSettings()["ssid"] = ""
					self:getSettings()["psk"] = ""
					self:storeSettings()
					self:popupmsg('RESETMSG',15000)
				end
			},
			{
				text = self:string("NETAPPLY"),
				style = 'item_choice',
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					log:info("Changing network settings...")
					self:popupscreen('NETAPPLYING','REBOOTWARNING')
					self:storeSettings()
					appletManager:callService("disconnectPlayer")
					os.execute("sqp_JogglerNetwork.sh apply &")
				end
			},
		})
	
	-- Don't save it if you've just twiddled a setting and left.	
	--window:addListener(EVENT_WINDOW_POP, 
	--	function()
	--		self:storeSettings()
	--	end
	--)

	window:addWidget(menu)
	self:tieAndShowWindow(window)
	menu:setHeaderWidget(headermsg)
	return window
	
end

-- Define the menu used in the initial setup process.
function setupShowJogglerNetwork(self, menuItem, setupNext)

	self:storeSettings()

	local group = RadioGroup()
	
	local nic = self:getSettings()["nic"]
	log:info(nic)

	local window = Window("text_list", self:string("NETWORK"))

	ipaddr = os.capture('sqp_JogglerNetwork.sh ip')
	headermsg = Textarea("help_text", ipaddr)

	menu = SimpleMenu("menu",
		{
			{
				text = self:string("CONTINUE"),
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					log:info("Accepted network settings.")
					self._topWindow = appletManager:callService("step3")
					return self.topWindow
				end
			},
			{
				text = self:string("WIREDCHOICE"),
				style = 'item_choice',
				check = RadioButton(
					"radio",
					group,
					function()
						self:getSettings()["nic"] = "eth0"
					end,
					(nic == "eth0")
				),
			},
			{
				text = self:string("WIRELCHOICE"),
				style = 'item_choice',
				check = RadioButton(
					"radio",
					group,
					function()
						self:getSettings()["nic"] = "wlan0"
					end,
					(nic == "wlan0")
				),
			},
			{
				text = self:string("WIRELSSID"),
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					self:ssidkeyWindow(menuItem, 'qwerty', Textinput.textValue("", 1, 99))					
				end
			},
			{
				text = self:string("WIRELPASS"),
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					self:passkeyWindow(menuItem, 'qwerty', Textinput.textValue("", 8, 99))					
				end
			},
			{
				text = self:string("NETRESET"),
				style = 'item_choice',
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					self:storeSettings()
					os.execute("sqp_JogglerNetwork.sh reset")
					self:getSettings()["nic"] = "eth0"
					self:getSettings()["ssid"] = ""
					self:getSettings()["psk"] = ""
					self:storeSettings()
					self:popupmsg('RESETMSG',15000)
				end
			},
			{
				text = self:string("NETAPPLY"),
				style = 'item_choice',
				sound = "WINDOWSHOW",
				callback = function(event, menuItem)
					log:info("Changing network settings...")
					self:popupscreen('NETAPPLYING','REBOOTWARNING')
					self:storeSettings()
					appletManager:callService("disconnectPlayer")
					os.execute("sqp_JogglerNetwork.sh apply &")
				end
			},
		})
	
	-- Don't save it if you've just twiddled a setting and left.	
	--window:addListener(EVENT_WINDOW_POP, 
	--	function()
	--		self:storeSettings()
	--	end
	--)

	window:addWidget(menu)
	self:tieAndShowWindow(window)
	menu:setHeaderWidget(headermsg)
	return window
	
end


-- Keyboard for SSID input
function ssidkeyWindow(self, menuItem, style, vals)

	local window = Window("input", menuItem.text)

	local textinput = Textinput("textinput", vals,
		function(_, value)
		
		--	log:warn("Input ", value)

			window:playSound("WINDOWSHOW")
			window:hide(Window.transitionPushRight)
			self:getSettings()["ssid"] = value

			return true
		end)
	
 	local backspace = Keyboard.backspace()
    local group = Group('keyboard_textinput', { textinput = textinput, backspace = backspace } )

    window:addWidget(group)
	window:addWidget(Keyboard('keyboard', style, textinput))
	window:focusWidget(group)

	self:tieAndShowWindow(window)
	return window
	
end


-- Keyboard for WPA passcode input
function passkeyWindow(self, menuItem, style, vals)

	local window = Window("input", menuItem.text)

	local textinput = Textinput("textinput", vals,
		function(_, value)
		
		--	log:warn("Input ", value)

			window:playSound("WINDOWSHOW")
			window:hide(Window.transitionPushRight)
			self:getSettings()["psk"] = value

			return true
		end)
	
 	local backspace = Keyboard.backspace()
    local group = Group('keyboard_textinput', { textinput = textinput, backspace = backspace } )

    window:addWidget(group)
	window:addWidget(Keyboard('keyboard', style, textinput))
	window:focusWidget(group)

	self:tieAndShowWindow(window)
	return window
	
end


-- Allows output of shell scripts to be captured.
function os.capture(cmd)
  local f = io.popen(cmd, 'r')
  local s = f:read('*a')
  f:close()
  return s
end


-- This is a simple on-screen message.
function popupmsg(self, warning, millis)

       log:info(self:string(warning))
 
       -- create a Popup object, using already established 'toast_popup_text' skin style
       local popupmessage = Popup('toast_popup_text')
 
       -- add message to popup
       local popupmessageMessage = Group("group", {
                       text = Textarea('toast_popup_textarea',self:string(warning)),
             })
       popupmessage:addWidget(popupmessageMessage)
 
       -- display the message for millis
       popupmessage:showBriefly(millis, nil, Window.transitionPushPopupUp, Window.transitionPushPopupDown)		

end


-- This is a full screen message. Use self.popup:hide() to get rid.
function popupscreen(self, warning, subwarning)

	log:info(self:string(warning))

    self.popup = Popup("waiting_popup")

	-- prevent exiting from the spinny
	self.popup:setAllowScreensaver(false)
	self.popup:setAlwaysOnTop(true)
	self.popup:setAutoHide(false)
	self.popup:ignoreAllInputExcept()

    self.popup:addWidget(Icon("icon_connecting"))
    self.popup:addWidget(Label("text", self:string(warning)))
    self.popup:addWidget(Label("subtext", self:string(subwarning)))
    self:tieAndShowWindow(self.popup)

end


--[[

=head1 LICENSE

This source code is public domain. It is intended for you to use as a starting
point to create your own applet.

=cut
--]]

