--[[
ģƣ¼
ģ鹦ܣ¼Ҷȡ¼
ģ޸ʱ䣺2017.04.05
]]

--ģ,
local base = _G
local string = require"string"
local io = require"io"
local os = require"os"
local rtos = require"rtos"
local audio = require"audio"
local sys = require"sys"
local ril = require"ril"
module(...)

--سõȫֺ
local smatch = string.match
local print = base.print
local dispatch = sys.dispatch
local tonumber = base.tonumber
local assert = base.assert

--RCD_ID ¼ļ
--RCD_FILE¼ļ
local RCD_ID,RCD_FILE = 1,"/RecDir/rec001"
--rcdingǷ¼
--rcdcb¼ص
--readingǷڶȡ¼
--duration¼ʱ룩
local rcding,rcdcb,reading,duration

--[[
print
  ӡӿڣļедӡrecordǰ׺
  
ֵ
]]
local function print(...)
	base.print("record",...)
end

--[[
getdata
  ȡ¼ļָλָ
  
		offsetnumberָͣλãȡֵΧǡ0  ļ-1
        lennumberָͣȣõĳȴļʣĳȣֻܶȡʣĳ
ֵָ¼ݣȡʧܣؿַ""
]]
function getdata(offset,len)
	local f,rt = io.open(RCD_FILE,"rb")
    --ļʧܣΪա
	if not f then print("getdata erropen") return "" end
	if not f:seek("set",offset) then print("getdata errseek") return "" end
    --ȡָȵ
	rt = f:read(len)
	f:close()
	print("getdata",string.len(rt or ""))
	return rt or ""
end

--[[
getsize
  ȡǰ¼ļܳ
  
ֵǰ¼ļܳȣλֽ
]]
local function getsize()
	local f = io.open(RCD_FILE,"rb")
	if not f then print("getsize erropen") return 0 end
	local size = f:seek("end")
	if not size or size == 0 then print("getsize errseek") return 0 end
	f:close()
    return size
end


--[[
rcdcnf
  AUDIO_RECORD_CNFϢ
  sucsucΪtrueʾʼ¼¼ʧ
ֵ
]]
local function rcdcnf(suc)
	print("rcdcnf",suc)
	if suc then
		rcding = true
	else
		if rcdcb then rcdcb() end
	end
end


--[[
rcdind
  ¼
  suctrue¼ɹfalse¼ʧ
ֵtrue
]]
local function rcdind(suc,dur)
	print("rcdind",suc,dur,rcding)	
    --¼ʧ  Ӧò¼Ϣ
	if not suc or not rcding then	
        --ɾ¼ļ
		delete()
	end
	duration = dur
	if rcdcb then rcdcb(suc and rcding,getsize()) end
	rcding=false
end


--[[
start
  ʼ¼
  secondsnumberͣ¼ʱλ룩
        cbfunctionͣ¼ص¼۳ɹʧܣcb
			÷ʽΪcb(result,size)resultΪtrueʾɹfalsenilΪʧ,sizeʾ¼ļĴСλֽڣ
ֵ
]]
function start(seconds,cb)
	print("start",seconds,cb,rcding,reading)
	if seconds<=0 or seconds>50 then
		print("start errseconds")
		if cb then cb() end
		return
	end
    --¼ڶȡ¼ֱӷʧ
	if rcding or reading then
		print("start erring")
		if cb then cb() end
		return
	end
	
	--¼־
	rcding = true
	rcdcb = cb
    --ɾǰ¼ļ
	delete()
    --ʼ¼
	audio.beginrecord(RCD_ID,seconds*1000)
end

--[[
delete
  ɾ¼ļ
  
ֵ
]]
function delete()
	os.remove(RCD_FILE)
end

--[[
getfilepath
  ȡ¼ļ·
  
ֵ¼ļ·
]]
function getfilepath()
	return RCD_ID.."&"..(duration or "0")
end

local procer = {
	AUDIO_RECORD_CNF = rcdcnf,
	AUDIO_RECORD_IND = rcdind,
}
--ע᱾ģעϢ
sys.regapp(procer)
