gulp = require('gulp')
path = require('path')
$ = require('gulp-load-plugins')(lazy: true)
logs = require('./logs')
del = require('del')
gutil = require('gulp-util')
fatalLevel = require('yargs').argv.fatal

ERROR_LEVELS = [
  'error'
  'warning'
]

HRTop    = '\n/********> Error'
HRBottom = '\n'

parseErrorToFriendlyString = (error) ->
  """
  > #{gutil.colors.bold.red('message')}: #{error?.message}  \r
  > #{gutil.colors.bold.red('plugin')}: #{error?.plugin}  \r
  > #{gutil.colors.bold.red('stack')}: #{error?.toString?()}  \r
  """

isFatal = (level) ->
  ERROR_LEVELS.indexOf(level) <= ERROR_LEVELS.indexOf(fatalLevel or 'error')

failedErrorHandler = (level) ->
  #if (isFatal(level)) {//process.exit(1); }

errorHandler =
  onWarning: (section, level) ->
    (error) ->
      failedErrorHandler(section, 'warning', error, level)
      gutil.colors.bold.red("#{section} failed to run")
      return

  onError: (section, level) ->
    (error, level) ->
      failedErrorHandler(section, 'error', error, level)
      gutil.log '\n\r' + gutil.colors.bold.red(HRTop) + '\r'
      gutil.log parseErrorToFriendlyString error
      gutil.log '\n\r' + gutil.colors.bold.red(HRBottom) + '\r'
      gutil.beep()
      @emit('end')
      return

  logger: (errors) ->
    header = '\n\r' + divider + '\r'
    output = header
    for name, message of errors
      output += "> #{gutil.colors.bold.red(name)}: #{message} \r"
    output += header
    header

  print: (name, message) ->
    gutil.log gutil.colors.bold.magenta(name) + ':'
    gutil.log '\n\r' + gutil.colors.bold.red(HRTop) + '\r'
    gutil.log message
    gutil.log '\n\r' + gutil.colors.bold.red(HRBottom) + '\r'
    return

  typeScriptLintReporter: (output, file, options) ->
    filePath = path.relative(__dirname, file.path).replace(/\.\.\//g, '')
    gutil.log """
    Found [#{gutil.colors.bold.red(output.length)}]
    errors in #{gutil.colors.bold.red(filePath)}
    """
    if output.length > 1
      errorHandler.print('TypeScript Error Log', output.map((file) ->
        startPos = file.startPosition
        endPos = file.endPosition
        return """
        filename: #{gutil.colors.magenta(file.name)}
        cause: #{gutil.colors.magenta(file.failure)}
        rule: #{file.ruleName} >>
        [line: #{startPos.line} | char: #{startPos.character} | pos: #{endPos.position}]
        """
      ).join('\r\n'))


module.exports = errorHandler
