--下面列出了常用的回调函数
--更多功能请阅读<<物联型LUA脚本API.pdf>>
local cjson = require "cjson"

local sc_home       = 0
local sc_wifiset    = 1
local sc_scanwifi   = 2
local sc_wificonnet = 3
local sc_dhcpset    = 4
local sc_dowm_pic   = 5
local sc_dowm_video = 6

local select_ssid = ""
local select_psw  = ""

local down_pic_info   = ""
local down_video_info = ""

local down_pic1_taskid  = 1
local down_pic2_taskid  = 2
local public_net_taskid = 1000
local down_video_taskid = 1024

local down_pic1_uri  = 'http://video.gz-dc.com/59a4d2393ff77.jpg'
local down_pic2_uri  = 'http://video.gz-dc.com/qj7118866528.jpg'
local public_net_uri = 'http://pv.sohu.com/cityjson?ie=utf-8'
local down_video_uri = 'http://video.gz-dc.com/%E5%A5%94%E9%A9%B0%E8%A7%86%E9%A2%91.mp4'

local surface  = 0

local down_dir = "a:/"

local videoplay_index = 0                                             --当前值
local videofilecount  = 0                                             --视频计数
local videofilenames  = {}                                            --视频文件名表
local videofileids    = {}  


function my_pic_down_Info()
	
	local show_x = 30
	local show_y = 118
	local show_w = 420 
	local show_h = 40
	local font_size  = 4
	local draw_text_color = 0xF800
	local align_mode = (0x01 << 2) | (0x00)
	
	local draw_pic_x = 30
	local draw_pic_y = 168
	local draw_pic_w = 420
	local draw_pic_h = 300
	
	draw_text(down_pic_info, show_x,  show_y, show_w , show_h, font_size, draw_text_color, align_mode) 
	draw_surface(surface, draw_pic_x, draw_pic_y, draw_pic_w, draw_pic_h)
end

function my_video_down_Info()
	
	local show_x = 30
	local show_y = 118
	local show_w = 420 
	local show_h = 40
	local font_size  = 4
	local draw_text_color = 0xF800
	local align_mode = (0x01 << 2) | (0x00)
	
	local draw_pic_x = 30
	local draw_pic_y = 168
	local draw_pic_w = 420
	local draw_pic_h = 300
	
	draw_text(down_video_info, show_x,  show_y, show_w , show_h, font_size, draw_text_color, align_mode) 
end

function my_getExtension(str)  
    return str:match(".+%.(%w+)$")  
end

-- 遍历目录
function my_listdir(rootpath)
	
    for entry in lfs.dir(rootpath) do  
        if entry ~= '.' and entry ~= '..' then                        --跳过目录中的.和..
            local path = rootpath .. '/' .. entry  
            local attr = lfs.attributes(path)                         --获取指定路径的属性
            if  attr.mode ~= 'directory' then
			    ext = my_getExtension(path)                              --获取扩展名
			    
			    if ext=='mp4' then
				  videofilenames[videofilecount] = path	
			      videofilecount = videofilecount + 1
			    end
            else
                my_listdir(path)  
            end
        end
    end
end

-- 播放下一个视频
function my_play_next_video()                                           --下一个视频

    print('--------------my_play_next_video-------------------')
	stop_video()
	
    videoplay_index = videoplay_index + 1	
	if videoplay_index >= videofilecount then
	    videoplay_index = 0
	end
	
	if videofilenames[videoplay_index] ~= nil
	then
		play_video(videofilenames[videoplay_index],1)
	end
end

--扫描wifi与显示
function my_scan_wifi()
	local ap_cnt = scan_ap()

	for i = 1, ap_cnt 
	do
		local ssid, security, quality = get_ap_info(i - 1)
		record_add(sc_scanwifi, 1, ssid..";"..quality..";")
	end
end

--初始化函数
function on_init()

	set_text(sc_wifiset, 2, "--")
	set_text(sc_wifiset, 5, "xxx.xxx.xxx.xxx")
	set_text(sc_wifiset, 7, "xxxxxxxxxxxx")
end

--系统回调函数，每秒执行一次
function on_systick()

	local text_secumode = ""
	local wifi_connect = get_network_state()
	local wifimode, secumode, ssid, password  = get_wifi_cfg()
	local dhcp, ipaddr, netmask, gateway, dns = get_network_cfg()
	
	--获取屏幕的MAC地址
	set_text(sc_wifiset, 7, get_wifi_mac())

	--有效WIFI名称长度，有设置WIFI连接
	if string.len(ssid) > 0
	then
		--已连接
		if wifi_connect ~= 0
		then
			if secumode == 0 
			then
				text_secumode = "(AUTO)"
			elseif secumode == 1 
			then
				text_secumode = "(WEP)"
			elseif secumode == 2
			then
				text_secumode = "(WPAPSK)"
			elseif secumode == 3
			then
				text_secumode = "(WPAPSK2)"
			end

			--停止播放动画，显示已连接的WIFI
			stop_animation(sc_home, 3)
			set_value(sc_home, 3, 4)
			set_text(sc_home, 4, ssid .. text_secumode)

			set_text(sc_wifiset, 2, ssid .. text_secumode)
			set_text(sc_wifiset, 5, ipaddr)
			set_text(sc_dhcpset, 4, ipaddr)
		
		--连接中
		else
			--播放动画，显示连接中
			play_animation(sc_home, 3)
			set_text(sc_home, 4, "连接“" .. ssid .. "”中...")

			set_text(sc_wifiset, 2, "连接“" .. ssid .. "”中...")
			set_text(sc_dhcpset, 4, "xxx.xxx.xxx.xxx")
			set_text(sc_wifiset, 5, "xxx.xxx.xxx.xxx")
		end
		
	--没设置WIFI连接
	else
		play_animation(sc_home, 3)
		set_text(sc_home, 4, '未连接')

		set_text(sc_wifiset, 2, '未连接')
		set_text(sc_wifiset, 5, "xxx.xxx.xxx.xxx")
		set_text(sc_dhcpset, 4, "xxx.xxx.xxx.xxx")
	end
	
end

function on_http_download (taskid, status)
	if taskid == down_pic1_taskid 
	then
		if status == 0 
		then
			down_pic_info = "Download Msg:pic1 -> download failed !!!"
		elseif status == 1 
		then
			down_pic_info = "Download Msg:pic1 -> download success, but save error !!!"
		elseif status == 2 
		then
			down_pic_info = "Download Msg:pic1 -> download success and save success"
			surface = load_surface(down_dir.."down1.jpg")
			redraw()	
		end

	elseif taskid == down_pic2_taskid 
	then
		if status == 0 
		then
			down_pic_info = "Download Msg:pic2 -> download failed !!!"
		elseif status == 1 
		then
			down_pic_info = "Download Msg:pic2 -> download success, but save error !!!"
		elseif status == 2 
		then
			down_pic_info = "Download Msg:pic2 -> download success and save success"
			surface = load_surface(down_dir.."down2.jpg")
			redraw()	
		end
		
	
	elseif taskid == down_video_taskid then
	
		if status  == 0 then 
			down_video_info =  "Download Msg : video ->  failed"
		
		elseif status  == 1 then
			down_video_info =  "Download Msg : video ->  success, but save error !!!"
		
		elseif status  == 2 then
			
			down_video_info = ""
			my_listdir(down_dir)
			my_play_next_video()
		end
	end	
end

function on_http_response(taskid,response)
	
	print("response ->"..response)
	
	local CityIpTb ={}
	local data_s, data_e = 0
	local ip, city = ''

	if public_net_taskid == taskid and response ~= ""
	then
		data_s =  string.find(response, "{", 1) 
		data_e =  string.find(response, "}", 1) 
		CityIpTb = cjson.decode(string.sub(response, data_s, data_e))
		
		ip   = CityIpTb['cip']
		city = CityIpTb['cname']
		
		set_text(sc_dowm_pic,  4, city)
		set_text(sc_dowm_pic, 10, ip)
	end

	--返回-1时，响应数据会通过串口发送给用户MCU
	--return -1
end

--用户通过触摸修改控件后，执行此回调函数。
--点击按钮控件，修改文本控件、修改滑动条都会触发此事件。
function on_control_notify(screen,control,value)
	
	if screen == sc_wifiset
	then
		if control == 3 and value == 1
		then
			record_clear(sc_scanwifi, 1) 
			my_scan_wifi()
		end

	elseif screen == sc_scanwifi 
	then
		if control == 1 
		then
			
			local token = 0x3B
			local get_wifi_info = record_read(sc_scanwifi, control, value)
			
			local path_len = string.len(get_wifi_info)
			for char_index = 1, path_len 
			do
				if  token == tonumber(string.byte(get_wifi_info, char_index, char_index))
				then
					select_ssid = string.sub(get_wifi_info, 1, (char_index - 1))
					set_text(sc_wificonnet, 3, "请输入“"..select_ssid.."”的密码")
					set_text(sc_wificonnet, 4, "")
					break;
				end
			end
			
			change_child_screen(sc_wificonnet)
			
		elseif control == 2 and value == 1
		then
			record_clear(sc_scanwifi, 1) 
			my_scan_wifi()
		end
	
	
	elseif screen == sc_wificonnet
	then
		if control == 2
		then
			select_psw = get_text(sc_wificonnet, 4)
			set_wifi_cfg(1, 0, select_ssid, select_psw)
			save_network_cfg()                                                     --保存网络配置                   
			change_screen(sc_wifiset)
		end

	elseif screen == sc_dhcpset 
	then                                                       
		if control == 2 
		then
			local dhcp, ipaddr, netmask, gateway, dns = get_network_cfg()
			if value == 1     
			then
				set_text(sc_dhcpset, 4, ipaddr)  
				set_visiable(sc_dhcpset, 5, 1) 
				
				set_network_cfg(1, ipaddr, netmask, gateway, dns) 
				save_network_cfg()	
			else
				set_text(sc_dhcpset, 4, "xxx.xxx.xxx.xxx")
				set_text(sc_wifiset, 5, "xxx.xxx.xxx.xxx")
				set_visiable(sc_dhcpset, 5, 0)  
			end 
			
		elseif control == 5
		then
			return 1
		
		elseif control == 14  and value == 1                                        -- 保存配置                                     
		then
			local dhcp    = 0
			local ipaddr  = get_text(sc_dhcpset, 7)
			local netmask = get_text(sc_dhcpset, 9)
			local gateway = get_text(sc_dhcpset, 11)
			local dns     = get_text(sc_dhcpset, 13)
			
			set_network_cfg(dhcp, ipaddr, netmask, gateway, dns)
			save_network_cfg()	
		end
	
	elseif screen == sc_dowm_pic
	then
		if control == 1 and value == 1
		then
			http_download(down_pic1_taskid, down_pic1_uri, down_dir.."down1.jpg")
			down_pic_info = "Download Msg:pci1, waiting!!!"
			if surface ~= 0 
			then
				destroy_surface(surface)
				surface = 0
			end
			
		elseif control == 2 and value == 1
		then
			http_download(down_pic2_taskid, down_pic2_uri, down_dir.."down2.jpg")
			down_pic_info = "Download Msg:pci2, waiting!!!"
 			if surface ~= 0 then
			    destroy_surface(surface)
				surface = 0
			end
			
		elseif control == 3 and value == 0
		then
			
			http_request(public_net_taskid, public_net_uri, 0)
			
			set_text(sc_dowm_pic,  4, 'waitting ...')
			set_text(sc_dowm_pic, 10, 'waitting ...')
		end
	
	elseif screen == sc_dowm_video
	then
		if control == 2 and value == 0
		then
			stop_video()
			http_download_bigfile(down_video_taskid, down_video_uri, down_dir..'BenZ.mp4')
			down_video_info =  "Requesting resources ... "
			
		elseif control == 1
		then
	       my_play_next_video() 
		end
	end
end

--当画面切换时，执行此回调函数，screen为目标画面。
function on_screen_change(screen)

	if screen == sc_dowm_video
	then
		my_play_next_video()
	end
end

function on_draw(screen)
	if screen == sc_dowm_pic
	then
		my_pic_down_Info()
	elseif screen == sc_dowm_video
	then
		my_video_down_Info()
	end
end

function on_sd_inserted(dir)
	
	down_dir = dir
	
	videofilenames = {} 
	videofilecount = 0
    my_listdir(down_dir)                                                --遍历目录
	videoplay_index = videofilecount
	
end

function on_sd_removed()
	
	videofilenames  = {}
    videoplay_index = 0
    videofilecount  = 0
	stop_video()
	
	down_dir = "a:/"
end