sub init()
    mBind(["Box", "search_bar", "editBox", "searchKeyboard", "keyBox", "searchList", "noResultsLabel", "ListFilters", "spinner", "presentListAnimation", "presentKeyboardAnimation", "labelText"])
    'getScene().backgroundColor = getTheme().backgroundColor
    'getScene().backgroundUri = "pkg:/images/overlay_darken.png"
	 getScene().backgroundColor = getTheme().backgroundSearchURI  ' Usamos bg_setting como backgroundUri

 
    m.fullWidth = getScreenSize().width
    m.fullHeight = getScreenSize().height
	
    'centerx = (m.fullWidth - m.Box.boundingRect().width) / 2
    'centery = (m.fullHeight - m.Box.boundingRect().height) / 2

    m.Box.translation = [ (m.fullWidth - m.Box.boundingRect().width) / 2 , 50]
	m.editBox.translation = [ 60 , (m.search_bar.boundingRect().height - m.editBox.boundingRect().height) / 2]
	m.editBox.hintText = tr("Pesquisar...")
	m.noResultsLabel.translation = [ (m.Box.boundingRect().width - m.noResultsLabel.boundingRect().width) / 2 , 0]
	
	m.searchKeyboard.domain = "email"
	m.searchKeyboard.mode = "ABC123Lower"
    m.searchKeyboard.textEditBox.hintText = tr(" Search...")
    m.searchKeyboard.textEditBox.voiceEnabled = true
    m.searchKeyboard.textEditBox.active = true
    m.searchKeyboard.textEditBox.active = true
	
    m.spinner.poster.uri="pkg:/images/loader.png"
    m.spinner.poster.width="128"
    m.spinner.poster.height="128"
	m.spinner.translation = [ (m.fullWidth-128) / 2 , (m.fullHeight-128) / 2]

    m.currentFilter = 0 '0=LIVE,1=MOVIES,2=SERIES
	m.currentSelected = 0

    m.top.ObserveField("visible", "onVisibleChange")
    m.top.observeField("content", "onListContentChange")
    m.top.observeField("filterSelected", "onFilterSelected")
	m.top.observeField("filterItemFocused", "onFilterItemFocused")
	m.top.observeField("searching", "onStartSearch")
	m.top.observeField("showSpinner","OnShowSpinnerChange")
	
	m.searchKeyboard.ObserveField("text", "onSearchQuery")
    m.searchKeyboard.observeFieldScoped("keyClose", "KeybordHide")
	
    createFilters()
    m.filters = ["get_live_streams","get_vod_streams", "get_series"]
	m.top.currentFilter = "get_live_streams"
	
    m.searchList.translation = [ 120 , (m.fullHeight-350) / 2]
	
	m.keyBox.width = m.searchKeyboard.boundingRect().width + 50
	m.keyBox.height = m.searchKeyboard.boundingRect().height + 50
	m.keyBox.translation = [(m.fullWidth-m.searchKeyboard.boundingRect().width) / 2, m.fullHeight - m.searchKeyboard.boundingRect().height * 1.3]
	
    m.searchKeyboard.translation = [25,25]
	m.global.cachesearch = invalid
	
end sub

sub OnVisibleChange() ' invoked when searchList change visibility
    if m.top.visible = true
        m.searchList.SetFocus(true) ' set focus to rowList if searchList visible
    end if
end sub

sub onSearchQuery(event as Object)
    ? "TEXT CHANGED TO: "; event.GetData()
    m.editBox.text = event.GetData()
    cursorPosition = m.editBox.cursorPosition
    m.editBox.cursorPosition = cursorPosition + 1

    ' Detener cualquier tarea de búsqueda previa
    if m.global.contentTask <> invalid 
        m.global.contentTask.control = "stop"
    end if 

    ' Restablecer contentType antes de iniciar una nueva búsqueda
    m.global.contentType = invalid  ' Restablecer contentType

    ' Establecer el tipo de contenido según el filtro seleccionado
    if m.top.currentFilter = "get_live_streams"
        m.global.contentType =  "live"
        m.global.play = "/live/" + m.global.user + "/" + m.global.pass + "/"
    else if m.top.currentFilter = "get_vod_streams"
        m.global.contentType =  "movie"  
        m.global.play = "/movie/" + m.global.user + "/" + m.global.pass + "/"
    else if m.top.currentFilter = "get_series"
        m.global.contentType =  "series"
        m.global.play = "/series/" + m.global.user + "/" + m.global.pass + "/"
    end if

    ' Ejecutar la búsqueda si el texto es lo suficientemente largo
    if event.GetData().len() > 2
        m.spinner.visible = true
        m.spinner.control = "start"
        m.global.contentTask = CreateObject("roSGNode", "SearchTask")
        m.global.contentTask.ObserveField("content", "onSearchRetrieved")
        m.global.contentTask.action = m.top.currentFilter
        m.global.contentTask.searchTerm = event.GetData()
        m.global.contentTask.control = "run"
    else
        m.spinner.visible = false
        m.spinner.control = "stop"  
    end if
end sub


sub onStartSearch(event)
	if m.top.currentFilter = "get_live_streams"
	    m.global.play = "/live/" + m.global.user + "/" + m.global.pass + "/"
	else if m.top.currentFilter = "get_vod_streams"	
	    m.global.play = "/movie/" + m.global.user + "/" + m.global.pass + "/"
	else if m.top.currentFilter = "get_series"
	    m.global.play = "/series/" + m.global.user + "/" + m.global.pass + "/"
	end if
    if event.getData()        
	    m.spinner.visible = true
	    m.spinner.control = "start"
	    m.global.contentTask = CreateObject("roSGNode", "SearchTask")
	    m.global.contentTask.ObserveField("content", "onSearchRetrieved")
		m.global.contentTask.action = m.top.currentFilter
		m.global.contentTask.searchTerm = m.editBox.text
	    m.global.contentTask.control = "run"
    end if
end sub

sub onSearchRetrieved(event)
    m.top.content = invalid
    content = event.getData()

    if content.getChild(0) <> invalid
        if content.getChild(0).GetChildCount() > 0
            m.noResultsLabel.visible = false
            m.top.content = content
        else
            m.top.showSpinner = false
            m.noResultsLabel.text = tr("No search results were found.")
            m.noResultsLabel.visible = true
        end if
    end if
end sub


sub onListContentChange()
    m.spinner.visible = false
    m.spinner.control = "stop"
    m.searchList.visible = true
end sub

sub createFilters()
    data = CreateObject("roSGNode", "ContentNode")
    items = [
	    { title: "canais", selected: true },
        { title: "filmes", selected: false },
        { title: "séries", selected: false }
    ]
    row = data.CreateChild("ContentNode")
    for each currentItem in items
        item = row.CreateChild("SearchFilterNode")
        item.labeltext = tr(currentItem.title)
        item.isselected = currentItem.selected
    end for
    m.ListFilters.content = data
end sub

sub onFilterSelected(event)
    itemIndex = event.getData()[1]
    
    ' Solo actualizamos si el filtro ha cambiado
    if itemIndex <> m.currentSelected
        m.top.content = invalid  ' Limpiar contenido de la pantalla
        m.global.cachesearch = invalid  ' Limpiar caché de búsqueda
        m.global.contentType = invalid  ' Restablecer contentType
    end if

    ' Guardamos el filtro seleccionado
    m.currentSelected = itemIndex
    m.top.currentFilter = m.filters[itemIndex]

    ' Asignar contentType según el filtro seleccionado
    if m.top.currentFilter = "get_live_streams"
        m.global.contentType = "live"
    else if m.top.currentFilter = "get_vod_streams"
        m.global.contentType = "movie"
    else if m.top.currentFilter = "get_series"
        m.global.contentType = "series"
    end if

    ' Si ya hay texto en el editBox, realizar una búsqueda
    if Len(m.editBox.text) >= 2 then 
        search()  ' Ejecutar la búsqueda
    else
        KeybordShow()  ' Mostrar teclado si no hay texto
    end if
end sub



sub onFilterItemFocused(event)
    itemIndex = event.getData()[1]
    rowContent = m.ListFilters.content.getChild(0)
    rowContent.getChild(m.currentFilter).isselected = false
    m.currentFilter = itemIndex
    rowContent.getChild(itemIndex).isselected = true
    m.top.currentFilter = m.filters[itemIndex] 
end sub

sub search()
    'KeybordShow()
	m.searchKeyboard.text = m.editBox.text
	m.top.searching = true
end sub

sub focusEditBox()
    animate = m.editBox.isInFocusChain()
    m.editBox.active = "false"
    if not animate return
    m.editBox.active = "true"
end sub

function KeybordShow()
    m.editBox.setFocus(false)
	m.keyBox.visible = "true"
	m.searchKeyboard.setFocus(true)
end function

function KeybordHide()
	m.keyBox.visible = "false"
	m.searchKeyboard.setFocus(false)
    m.editBox.setFocus(true)
    focusEditBox()
end function

sub OnShowSpinnerChange(event)
  if event.getData()
    m.spinner.visible = true
    m.spinner.control = "start"
  else
    m.spinner.visible = false
    m.spinner.control = "stop"
  end if
end sub

function onKeyEvent(key as string, press as boolean) as boolean
    handled = false
    if press and m.top.isInFocusChain()
        if key = "up" 
		    if m.ListFilters.isInFocusChain()
			    m.ListFilters.setFocus(false)
			    m.editBox.setFocus(true)
				focusEditBox()
			else if m.searchList.isInFocusChain()
			    m.searchList.setFocus(false)
			    m.ListFilters.setFocus(true)
			end if
            handled = true
        else if key = "down"
		    if m.editBox.isInFocusChain()
			    m.editBox.setFocus(false)
				m.ListFilters.jumpToItem = m.currentFilter
			    m.ListFilters.setFocus(true)
				focusEditBox()
			else if m.ListFilters.isInFocusChain()
			    m.ListFilters.setFocus(false)
			    m.searchList.setFocus(true)
			end if
            handled = true
       ' else if key = "left" and m.searchList.hasFocus()
            'focusKeyboard(true)
        '    handled = true
        'else if key = "right" and (m.searchKeyboard.isInFocusChain() or m.ListFilters.isInFocusChain()) and m.searchList.content <> invalid and m.searchList.visible
            'focusList(true)
       '     handled = true
		else if key = "OK" then
		    if not m.ListFilters.isInFocusChain()
			    KeybordShow()
			else if m.searchList.isInFocusChain()
			    'm.searchList.setFocus(false)
			    'm.ListFilters.setFocus(true)
			end if
		    handled = true
        else if key = "back" 
		    if m.searchKeyboard.isInFocusChain()
                KeybordHide()
                handled = true
			end if
        end if
    end if
    return handled
end function
