Window = {}
Window.__index = Window

is_moving_global = false

function Window:new(app, x, y, width, height)
    local window = setmetatable({}, self)
    
    window.app = app
    window.x = x
    window.y = y
    window.width = width
    window.height = height
    window.is_moving = false
    window.last_mouse_x = 0
    window.last_mouse_y = 0
    
    app:setWindow(window)
    app:init()

    return window
end

function Window:update()
    local mx, my = mouse.getPosition()

    if (mx > 1 and my > 1)
        and (mx >= self.x and mx <= self.x + self.width and my >= self.y and my <= self.y + 20)
    then
        if(mouse.isDown(1) and self.is_moving == false and is_moving_global == false) then
            is_moving_global = true
            self.is_moving = true
            self.last_mouse_x = mx
            self.last_mouse_y = my
        end
    end

    if(self.is_moving) then
        self.x = self.x + mx - self.last_mouse_x
        self.y = self.y + my - self.last_mouse_y
        self.last_mouse_x = mx
        self.last_mouse_y = my
    end

    if(mouse.isDown(1) == false) then
        self.is_moving = false
        is_moving_global = false
    end

    return self.is_moving
end

function Window:draw(is_active)
    -- border
    graphics.setColor(0.4, 0.4, 0.4)
    if is_active then graphics.setColor(0.4, 0.4, 0.9) end
    graphics.rectangle("fill", self.x - 2, self.y - 2, self.width + 4, self.height + 4)

    -- window
    graphics.setColor(0.8, 0.8, 0.8)
    graphics.rectangle("fill", self.x, self.y, self.width, self.height)

    -- window top bar
    graphics.setColor(0.4, 0.4, 0.4)
    graphics.rectangle("fill", self.x, self.y, self.width, 20)

    -- close window button
    graphics.setColor(1, 0.4, 0.4)
    graphics.rectangle("fill", self.x + self.width - 15, self.y + 5, 10, 10)

    self.app:draw(self.x, self.y + 20, self.width, self.height - 20)
end