InputLine = copy_table(Text)

function InputLine:init(def, view)
    Text.init(self, def, view)
    self.focus = def.focus or true
    self.max_width = def.max_width
    self.max_length = def.max_length
    self.timer = 0
    self.click_sound = def.click_sound
    self.numeric = def.numeric
    self.alphanumeric = def.alphanumeric
    self.activation_code = def.activation_code

    if def.on_finished then
        self.call_on_finished = view[def.on_finished]
    end
end


function InputLine:filter_characters(str)
    if self.numeric then
        return string.gsub(str, "[^0-9\.]", "")
    elseif self.alphanumeric then
        return string.gsub(str, "[^0-9a-zA-Z\-\ ]", "")
    elseif self.activation_code then
        return string.upper(string.gsub(str, "[^a-tA-T]", ""))
    else
        return string.gsub(str, "[^0-9a-zA-Z\-\!\?\'\.\ ]", "")
    end
end


function InputLine:update(dt)
    Text.update(self,dt)
    if self.focus then
        self.timer = self.timer + dt
        if self.timer > 0.8 then
            self.timer = self.timer - 0.8
        end

        local chars = kbd_chars()
        if chars then
            chars = self:filter_characters(chars)
            if #chars > 0 then
                local new_text = self.text..chars

                if not self.max_length or #new_text <= self.max_length then
                    local width = gfx_text_size(self.font, new_text, self.align)
                    if not self.max_width or width <= self.max_width then
                        self.text = new_text
                        if self.click_sound then snd_play_sound(self.click_sound) end
                    end
                end
            end
        end
        
        if kbd_struck("backspace") or kbd_struck("del") then
            self.text = self.text:sub(1, -2)
            if self.click_sound then snd_play_sound(self.click_sound) end
        end
        
        if kbd_struck("enter") then
            if self.call_on_finished then
                self.call_on_finished(self.view, self)
            end
        end
    end
end


function InputLine:render()
    -- if self.max_width then gfx_render_box(self.x, self.y, self.max_width, 10, 0.6, 0, "ffffff") end

    local text
    if self.activation_code then
        text = ""
        for i = 1, string.len(self.text) do
            cha = string.sub(self.text, i, i)
            text = text..cha
            if i % 4 == 0 and i < 16 then
                text = text.." - "
            end
        end
    else
        text = self.text
    end
    
    if self.timer >= 0.3 then
        text = text.."|"
    end
    gfx_render_text(self.font, self.x, self.y, text, self.align, self.w, self.h, self.alpha, self.color)
end


function InputLine:get_text()
    return trim(self.text)
end
