'use strict'

let gen = require( './gen.js' )

let proto = {
  basename:'loop',

  gen() {
    let conditional = gen.getInput( this.inputs[0] ),
        block = this.inputs[1],
        defaultout = this.inputs[2],
        out = `  var ${this.name}_out = ${defaultout}\n`,
        blockName, output

    debugger
    if( typeof block === 'number' ){
      blockName = null
    }else{
      if( gen.memo[ block.name ] === undefined ) {
        console.log( 'localizing block' )
        // used to place all code dependencies in appropriate blocks
        gen.startLocalize()

        console.log( 'blcok:', block )
        gen.getInput( block )

        block = gen.endLocalize()
        blockName = block[0]
        console.log( 'BLOCK:', block )
        block = block[ 1 ].join('')
        block = '  ' + block.replace( /\n/gi, '\n  ' )
      }else{
        block = ''
        blockName = gen.memo[ preblock.name ]
      }
    }

    console.log( 'blockName:', blockName )
    output = blockName === null 
      ? `  ${this.name}_out = ${block}` 
      : `${block}  ${this.name}_out = ${blockName}`
    
    out += ' '

    out += 
` while( ${conditional} === 1 ) {
  ${output}
  }`

    out += `\n`

    gen.memo[ this.name ] = `${this.name}_out`

    return [ `${this.name}_out`, out ]
  }
}

module.exports = ( condition, block, defaultout=0 ) => {
  const ugen = Object.create( proto )

  Object.assign( ugen, {
    uid:     gen.getUID(),
    inputs:  [ condition, block, defaultout ],
  })
  
  ugen.name = `${ugen.basename}${ugen.uid}`

  return ugen
}
