React = require 'react'
{div} = React.DOM

module.exports =

  getInitialState: ->
    {
      layout: 2
    }
  
  componentWillMount: ->
    # Use the MIN_MODULE_WIDTH defined on the component or default to 550
    @MIN_MODULE_WIDTH = @MIN_MODULE_WIDTH or 500
    
    window.addEventListener 'resize', @measureColumns
    @measureColumns()

  componentWillUnmount: ->
    window.removeEventListener 'resize', @measureColumns

  # Detirmines how many columns should be drawn on mount and resize
  # Sets the layout state when appropriate
  measureColumns: ->
    {layout} = @state
    
    width = window.innerWidth
    newColumnCount = Math.floor width/@MIN_MODULE_WIDTH
    newColumnCount = if newColumnCount is 0 then 1 else newColumnCount
    newColumnCount = if newColumnCount is 5 then 4 else newColumnCount
    
    # Set the layout state when the layout has changed
    if newColumnCount isnt layout
      @setState
        layout: newColumnCount

  
  featureIsEnabled: (feature, features) ->
    unless feature? then return false
    unless feature.subdeps? then return feature.actions[feature.primaryAction] 

    subDepConditionMet = no
    for dep, action of feature.subdeps
      if features[dep]?.actions[action]
        subDepConditionMet = yes
        break

    feature.actions[feature.primaryAction] and subDepConditionMet



  # To be called from within render
  # Builds the array of columns components with the modules
  # in the appropriate order for the current layout
  buildColumns: ->
    {layout} = @state
    {mpi} = @props.params
    {authorityId, patientId} = @props.location.query
    {features} = @getStore 'loggedInUser'
    activeModules = @makeModuleList()

    # Always use the 2 column layout when there are fewer active modules than columns
    layout = if activeModules.length < layout then layout - 1 else layout

    columns = []
    columns.push([]) for c in [0...layout]

    col = 0
    for factory, i in activeModules
      col = if col is layout then 0 else col
      columns[col].push factory {
        key: "module-#{i}"
        mpi: mpi
        authorityId: authorityId
        patientId: patientId
      }
      col += 1
    
    columnEls = []
    columnCount = 0
    for moduleList, i in columns
      columnEls.push div {
        key: "column-#{columnCount}"
        className: "column layout-#{layout} col-#{columnCount}"
      }, moduleList
      columnCount += 1

    columnEls
