// Template loading code
////////////////////////////////////////////////////////////////////////////////


// Reload the cached files when it changes.
function onFileChange( filename, filePath, cb ){
  function exec( event ){
    if( process.env.NODE_ENV !== 'production' ){
      console.error( 'Loading template:'.yellow, filePath.grey );
    }

    try{
      if( cb ){
        cb( null, fs.readFileSync( filePath, 'utf8' ) );
      }
      else{
        dust.compileFn( fs.readFileSync( filePath, 'utf8' ), filename );
      }
    }
    catch( e ){
      console.error( 'Error loading template file: '.red );
      console.error( e );
      if( cb ){
        cb( e );
      }
    }
  }

  return cb ? exec() : exec;
}

//load files directly from the file system.
function onLoad( basePath ){
  return function( name, cb ){

    var fullPath = path.join( basePath, name );

    if( fs.existsSync( fullPath ) ){
      onFileChange( name, fullPath, cb );
      fs.watch( fullPath, { persistent: false }, onFileChange( name, fullPath) );
    }
    else{
      cb( new Error( 'File ' + fullPath + ' does not exist.') );
    }
  };
}