Transition = {}

function Transition:init(next_view, options, transition)
    self.next_view = next_view
    self.ani = Animator:new()
    self.options = options

    input_enable(false)

    local time = 0.5
    if type(transition) == "table" then
        self.mode = transition.mode or "fade"
        time = transition.time or time
    else
        self.mode = transition or "fade"
    end

    if self.mode == "blend" then
        if fw.view then
            self.bitmap = gfx_create_bitmap(800, 600, false)
            if self.bitmap then
                gfx_render_target(self.bitmap)
                fw:recursive_render(fw.view)
                gfx_render_target(nil)
                self.ani:key("overlay", {{0, 1}, {time, 0}})
                self:switch()
            else
                self.mode = "fade"
            end
        else
            self.mode = "fade"
        end
    end

    if self.mode == "fade" then
        if fw.view then
            self.ani:key("blackness", {{0, 0}, {time, 1}, {time*2, 0}})
            self.ani:key("switch", {{0, -1}, {time, 0}, {time*2, 1}})
        else
            self.ani:key("blackness", {{0.0, 1}, {time, 0}})
            self.ani:key("switch", {{0.0, 0}, {time, 1}})
        end
    end
end


function Transition:destroy()
    input_enable(true)
    if self.bitmap then
        gfx_release_bitmap(self.bitmap)
    end
end


function Transition:switch()
    self.switched = true
    if fw.view then
        fw:destroy_view_chain(fw.view)
    end
    fw.view = create_view(self.next_view, self.options)

    if toggle_full_screen_at_transition then
        gfx_full_screen(toggle_full_screen_at_transition)
        toggle_full_screen_at_transition = nil
    end
    log("Switched view")
end


function Transition:update(dt)
    self.ani:update(dt)

    if not self.switched and self.ani.val.switch >= 0 then
        self:switch()
    end

    if self.ani:is_finished() then
        self.to_destroy = true
    end

    if self.switched then
        -- jesli update mialby byc odblokowany to najlepiej na czas trwania
        -- transition zablokowac mu input (myszka, klawiatura), zeby
        -- cos sie nie pochrzanilo jak user zacznie za szybko klikac
        fw.view:update(dt)
    end
end


function Transition:render()
    if fw.view then
        fw:recursive_render(fw.view)
    end
    if self.mode == "fade" then
        gfx_render_box(0, 0, 800, 600, self.ani.val.blackness, 0, "000000")
    elseif self.mode == "blend" then
        gfx_render_sprite(self.bitmap, "main", 400, 300, self.ani.val.overlay)
    end
end
