local Event = require("gfx.event")
local Element = require("gfx.element")
local Prop = require("gfx.prop")
local Orientation = require("gfx.prop.orientation")
local Children = require("gfx.prop.children")
local List = Prop.attach(Prop.attach(Element:new(), Orientation), Children)

function List:adjustPositions(from)
  from = from or 1
  local vertical = self:isVertical()
  local newDims = 1
  local getDim = vertical and function(e) return e:getHeight() end or function(e) return e:getWidth() end
  local children = self:_children()
  for i=1,from-1 do
    newDims = newDims + getDim(children[i])
  end

  local setDim = vertical and function(e, dim) e:setY(dim) end or function(e, dim) e:setX(dim) end
  for i=from,#children do
    setDim(children[i], newDims)
    newDims = newDims + getDim(children[i])
  end
end

function List:insertChild(child, atIndex)
  self:_addChild(child, atIndex)
end

function List:removeChild(child)
  return self:_removeChild(child)
end

local function maxOrSum(shouldSum, iter, getValue)
  if shouldSum then
    local sum = 0
    for _,v in iter() do
      sum = sum + getValue(v)
    end
    return sum
  else
    local max = 0
    for _,v in iter() do
      max = math.max(max, getValue(v))
    end
    return max
  end
end

function List:getHeight()
  local lSelf = self
  return maxOrSum(self:isVertical(), function() return lSelf:_iterateChildren() end, function(e) return e:getHeight() end)
end

function List:getWidth()
  local lSelf = self
  return maxOrSum(self:isHorizontal(), function() return lSelf:_iterateChildren() end, function(e) return e:getWidth() end)
end

function List:_reload()
  Element._reload(self)

  -- Reload child windows
  local win = self:_getWindow()
  for _,child in self:_iterateChildren() do
    if child:_getWindow() ~= win then
      child:setParent(win)
    end
  end

  self:adjustPositions()
end

return List