/**
 * Stack component
 *
 * Generated by coz on 8/13/2016,
 * from a template provided by apeman-asset-templates.
 *
 * @class Stack
 */
'use strict'

import React from 'react'
import defineDebug from 'debug'
import { ApViewStack } from 'apeman-react-basic'
import classnames from 'classnames'
import { IconClasses, StackWays } from 'ore-fol-enums'
import { spinalcase } from 'stringcase'
import StackView from './stack_view'

const { CLOSE_ICON, BACK_ICON } = IconClasses
const { PUSH_LEFT_WAY } = StackWays

const debug = defineDebug('project:fragment:frame')

/** @lends Stack */
const Stack = ({
  lang,
  l,
  signed,
  views,
  srvc,
  stackName,
  modalStackName,
  className, fixed
}) => {
  let empty = views.length === 0
  return (
    <ApViewStack { ...{ fixed } }
                 className={ classnames('stack', { 'empty-stack': empty }, className, `${spinalcase(stackName.replace(/^stack:/, ''))}-stack`) }>
      {
        views.filter(Boolean).map(({ key, name, params, way }) => (
          <StackView { ...{ name, params, way } }
                     stackName={ stackName }
                     key={ key || name }
                     shared={ { l, lang, signed, srvc } }
                     bundle={ Stack.viewBundle({ srvc, stackName, modalStackName, way }) }
          />
        ))
      }
    </ApViewStack>
  )
}

Object.assign(Stack, {
  viewBundle: ({ srvc, stackName, modalStackName, way }) => {
    const { pushView, popView, popAllViews } = srvc.viewService
    let cacheKey = [ stackName, modalStackName, way ].join('-')
    let cache = Stack._viewBundleCache[ cacheKey ]
    if (cache) {
      return cache
    }
    let bundle = {
      pushViewToCurrentStack: pushView.bind(pushView, stackName),
      popViewFromCurrentStack: popView.bind(popView, stackName),
      popAllViewsFromCurrentStack: popAllViews.bind(popAllViews, stackName),
      pushViewToModalStack: pushView.bind(pushView, modalStackName),
      popViewFromModalStack: popView.bind(popView, modalStackName),
      popAllViewsFromModalStack: popAllViews.bind(popAllViews, stackName),
      popIcon: way === PUSH_LEFT_WAY ? BACK_ICON : CLOSE_ICON
    }
    Stack._viewBundleCache[ cacheKey ] = bundle
    return bundle
  },

  _viewBundleCache: {}
})

export default Stack
