import { Logger, transports } from 'winston'
import partial from 'lodash/partial'

export function use(options = {}, next) {
  if(this.logger) {
    next()
  } else {
    attach(this)
    next()
  }
}

export function attach(project, options = {}) {
  if (project.logger) { return project.logger }

  const debug = !!(options.debug || project.get('environment.SKYPAGER_DEBUG') || project.get('argv.debug'))

  let _transports = [
    new transports.File({
      name: `project`,
      filename: project.join('log', `project.${ project.env }.log`),
      timestamp: true,
      json: false,
      prettyPrint: false,
      maxSize: 1024
    })
  ]

  if (project.result('console', () => !!options.console)) {
    _transports.push(
      new transports.Console({
        name: 'console',
        colorize: true,
        prettyPrint: true,
        level: debug ? 'debug' : 'info'
      })
    )
  }

  project.hide(
    'logger',
    new Logger({ level: 'debug', transports: _transports }),
    false
  )

  project.hide(
    'streamer',
    new Logger({ level: 'debug', transports: [
      new transports.File({
        name: `json`,
        filename: project.join('log', `${project.env}-${project.name}.json.log`),
        timestamp: true,
        json: true,
        prettyPrint: false
      }),
      new transports.File({
        name: `pretty-json-stream`,
        filename: project.join('log', `${project.env}-${project.name}.pretty.json.log`),
        timestamp: true,
        json: true,
        prettyPrint: true,
        colorize: true,
      })
    ]})
  )

  project.hide('info', (...args) => {
    project.logger.info(...args)

    if (project.getOption('streamLogs')) {
      project.streamer.info(...args)
    }
  })

  project.hide('error', (...args) => {
    project.logger.error(...args)

    if (project.getOption('streamLogs')) {
      project.streamer.error(...args)
    }
  })

  project.hide('debug', (...args) => {
    project.logger.debug(...args)

    if (project.getOption('streamLogs')) {
      project.streamer.debug(...args)
    }
  })

  project.hide('log', (...args) => {
    project.logger.info(...args)

    if (project.getOption('streamLogs')) {
      project.streamer.info(...args)
    }
  })

  project.hide('warn', (...args) => {
    project.logger.warn(...args)

    if (project.getOption('streamLogs')) {
      project.streamer.warn(...args)
    }
  })

  return project
}

export default attach

const { assign, defineProperty } = Object
