local VERSION = "2.2"

local VALUE = 0
local COMBO = 1

local TA_LEFT = 0
local TA_RIGHT = 1

local fields = {}

local printText = (0x800 + 0x02)
local hPWin = 0
local current
local editMode = false
local modifications = {}
local refreshState = 0
local pageOffset = 0
local page = 1
local pages = {}
local field

local b4Power
local b5Band
local b6Channel

local configFields = {
  {"Channel:",COMBO, 0x80, 1, {"CH1","CH2","CH3","CH4","CH5","CH6","CH7","CH8"}},
  {"Band:", COMBO, 0X80, 1, {"A", "B", "C", "D", "E", "F"}},
  {"Power:", COMBO, 0X80, 1, {"PIT", "25mW", "200mW", "600mW"}},
  {"All Frq:", COMBO, 0X80, 1, {"YES", "NO"}}
}

local frequency = {
  {"5865M", "5733M", "5705M", "5740M", "5658M", "5362M"}, 
  {"5845M", "5752M", "5685M", "5760M", "5695M", "5399M"},
  {"5825M", "5771M", "5665M", "5780M", "5732M", "5436M"},
  {"5805M", "5790M", "5645M", "5800M", "5769M", "5473M"},
  {"5785M", "5809M", "5885M", "5820M", "5806M", "5510M"},
  {"5765M", "5828M", "5905M", "5840M", "5843M", "5547M"},
  {"5745M", "5847M", "5925M", "5860M", "5880M", "5584M"},
  {"5725M", "5866M", "5945M", "5880M", "5917M", "5621M"}
}



local function telemetryRead(field)  
  return sport.TelemetryPush(0x13, 0x30, 0xe10, field)
end

local function telemetryIdle(field)
  return sport.TelemetryPush(0x13, 0x21,0xe10,field)
end

local function telemetryUnIdle(field)
  return sport.TelemetryPush(0x13, 0x20,0xe10,field)
end

local function telemetryWrite(field,value)   
  return sport.TelemetryPush(0x13, 0x31,0xe10,field+value*256)
end


-- Redraw the current page
local function redrawFieldsPage(hWin)

  if #fields > NUM_PER_PAGE then
    drawScrollbar(hWin, #fields, NUM_PER_PAGE, pageOffset)
  end
  
	for index = 1, NUM_PER_PAGE, 1 do
		local field = fields[pageOffset+index]
		if field == nil then
		  break
		end		
    
    drawText(hWin, index-1, field[1], TA_LEFT)
    
		if field[4] == nil then
			if field[2] == VALUE then
				drawEdit(hWin, index-1, "---")
			elseif field[2] == COMBO then			
				drawDropdown(hWin, index-1, 0, "---")
			end	
		else
      if field[2] == VALUE then
        drawEdit(hWin, index-1, field[4], field[5], field[6], 0) 
      elseif field[2] == COMBO then
        if field[4] >= 0 and field[4] < #(field[5]) then		
          local attr = field[5][1].."|"
          for index2 = 2,  #(field[5]), 1 do
            attr = attr..field[5][index2]
            if index2 <= #(field[5]) then
              attr = attr.."|"
            end
          end		
          
        --setWValue(hPWin, printText, "chan="..fields[1][4].." 2="..b5Band.." 3="..b6Channel)
        drawDropdown(hWin, index-1, field[4], attr)
        end
      end
    end
  end

     
  local a1 =   configFields[1][4]
  local a2 =   configFields[2][4]
  local a3  =   frequency[a1+1][a2+1]
 
  --lcd.drawText(1, 30+20*5,"Frequency:")
  --lcd.drawText(COLUMN_2, 30+20*5, a3 , attr)
  drawText(hWin, #fields, "Frequency:", TA_LEFT) 
  drawEdit(hWin, #fields, a3)
  
  
  --lcd.drawText(1,30+20*6,"Version:")
  --lcd.drawText(COLUMN_2, 32+20*6,VERSION)
  drawText(hWin, #fields+1, "Version:", TA_LEFT) 
  drawEdit(hWin, #fields+1, VERSION)

end


local function refreshNext()  
  if refreshState == 0 then  
    if #modifications > 0 then      
      telemetryWrite(modifications[1][1], modifications[1][2])
      table.remove(modifications,1)--modifications[1] = nil
      refreshIndex = 0
    elseif refreshIndex < #fields then
			local field = fields[refreshIndex + 1]      
			if telemetryRead(field[3]) == true then     
				refreshState = 1
				telemetryPopTimeout = getTime() + 200 -- normal delay is 500ms
			end
    end
	elseif refreshState == 1 then
		local appId, primId, value = sport.TelemetryPop()    
      
    if appId == 0x0e10 and primId == 0x32 then          
      local fieldId = value % 256            
      local field = fields[refreshIndex + 1]        
      if fieldId == field[3] then
      local value = math.floor(value / 256)
      b6Channel = value % 256
      value = math.floor(value / 256)
      b5Band = value % 256
      value = math.floor(value / 256)
      b4Power = value
      fields[1][4] = b4Power
      fields[2][4] = b5Band
      if b6Channel > 9 then
         bAllFrq = 1
         b6Channel = b6Channel - 10
      else
        bAllFrq = 0
      end                                   
      fields[3][4] = b6Channel
      fields[4][4] = bAllFrq 
      end
      refreshIndex = refreshIndex + 1
      refreshState = 0 
		elseif getTime() > telemetryPopTimeout then 
			refreshState = 0
		end
  end
end

-- Main
local function runFieldsPage(hWin, Key)  
  redrawFieldsPage(hWin)
  return 0
end

local function runConfigPage(hWin, Key)
  fields = configFields
  local result
  if false == editMode then
    result = runFieldsPage(hWin, Key)          
  end
  return result
end


-- Select the next or previous page
local function selectPage(step)
  page = 1 + ((page + step - 1 + #pages) % #pages)
  
	current, edit, refreshState, refreshIndex, pageOffset = 1, false, 0, 0, 0
  
  clearAll(hPWin)  
end

-- Select the next or previous editable field
local function selectField(step)
  local retValue = 1
  current = current + step  
  
  if current > #fields then
    current = #fields 
  elseif current < 1 then  
    current = 1
  elseif current > NUM_PER_PAGE + pageOffset then
    pageOffset = current - NUM_PER_PAGE
  elseif current <= pageOffset then
    pageOffset = current - 1 
  else
    retValue = 0
  end
  
  return retValue
end


local function updateField(field)
  
  local value   
  fields[1][4]=getWValue(0, fields[1][2])
  b6Channel = fields[1][4]
  
  fields[2][4] = getWValue(1, fields[2][2])
  b5Band = fields[2][4]
  
  fields[3][4] = getWValue(2, fields[3][2])
  b4Power = fields[3][4]
  
  fields[4][4] = getWValue(3, fields[3][2])
  b4Power = b4Power + (fields[4][4]) * 10
  
  value = b6Channel*256*256 + b5Band * 256 +b4Power
  modifications[#modifications+1] = { field[3],value } 
end

-- Init
function init()
	current, edit, refreshState, refreshIndex = 1, false, 0, 0
  
	pages = {
		runConfigPage
	}
  
  telemetryIdle(0x80)
end

--run
function runLua(hWin, Key)
  hPWin = hWin
  local result = 0
    
	if Key == 0 then
		result = 0
	elseif Key == 1 then     
    --result = runConfigPage(hWin,Key)
  elseif Key == KEY_ENT then 
  
    if true == editMode then      
      updateField(fields[current])
    end   

    editMode = not editMode      
  elseif Key == KEY_TAB then
    result = selectField(1)
  elseif Key == KEY_BACKTAB then
    result = selectField(-1)    
  elseif Key == KEY_PG_DN then
    --selectPage(1)
  elseif Key == KEY_PG_UP then
    --selectPage(-1)
  elseif Key == KEY_RTN_R then 
    clearAll(hWin)
  else 
    
	end  
  
  drawTitle(hPWin, "gTrans", page, #pages)
  
  pages[page](hWin,Key)
  
	refreshNext()

	return result
 end
