const checkForDuplicateIssue = require('./utils/check-for-duplicate-issue')
const handlerSetup = require('./utils/handler-setup')
const { assignFlow, lineBreak, truncate } = require('./utils/helpers')
const chunkDiff = require('./utils/chunk-diff')
const parseChunk = require('./utils/parse-chunk')
const reopenClosed = require('./utils/reopen-closed')
const getDeets = require('./utils/get-deets')
const { issue } = require('./templates')
const checkForBody = require('./utils/check-for-body')

module.exports = async context => {
  // Only trigger push handler on pushes to master
  if (context.payload.ref !== `refs/heads/${context.payload.repository.master_branch}`) {
    return
  }

  // Do not trigger on merge commits
  const commit = await context.github.gitdata.getCommit(context.repo({commit_sha: context.payload.head_commit.id}))
  if (commit.data.parents.length > 1) return

  const [
    { regex, config, labels },
    files
  ] = await Promise.all([
    handlerSetup(context),
    chunkDiff(context)
  ])

  const keywords = Array.isArray(config.keyword) ? config.keyword : [config.keyword]
  const TITLE_REG = new RegExp(`.+()\\s(?<keyword>${keywords.join('|')})\\s(?<title>.*)`)
  const excludePattern = config.exclude

  let match
  for (const file of files) {
    if (file.to === '.github/config.yml') {
      context.log.debug('Skipping .github/config.yml')
      continue
    } else if (excludePattern && new RegExp(excludePattern).test(file.to)) {
      context.log.debug('Skipping ' + file.to + ' as it matches the exclude pattern ' + excludePattern)
      continue
    }

    for (const chunk of file.chunks) {
      for (const indexStr in chunk.changes) {
        const index = parseInt(indexStr, 10)
        const change = chunk.changes[index]
        const matches = TITLE_REG.exec(change.content)
        if (!matches) continue

        const { title, keyword } = matches.groups

        const deets = getDeets({ context, config, chunk, line: change.ln || change.ln2 })

        // Prevent duplicates
        const existingIssue = await checkForDuplicateIssue(context, title)
        if (existingIssue) {
          context.log(`Duplicate issue found with title [${title}]`)
          await reopenClosed({ context, config, issue: existingIssue }, { keyword, sha: deets.sha, filename: file.to })
          continue
        }

        // Actually create the issue
        let body = issue(context.repo({
          sha: deets.sha,
          assignedToString: deets.assignedToString,
          range: deets.range,
          filename: file.to,
          keyword,
          body: checkForBody(chunk.changes, index, config)
        }))

        await context.github.issues.create(context.repo({ title: truncate(title), body, labels, ...assignFlow(config, deets.username) }))
      }
    }
  }

  return

  for (let i = 0; i < chunks.length; i++) {
    const chunk = chunks[i]

    while ((match = regex.exec(chunk)) !== null) {
      const parsed = parseChunk({ match, context, config })

      if (parsed.filename === '.github/config.yml') {
        context.log.debug('Skipping .github/config.yml')
        continue
      } else if (excludePattern && new RegExp(excludePattern).test(parsed.filename)) {
        context.log.debug('Skipping ' + parsed.filename + ' as it matches the exclude pattern ' + excludePattern)
        continue
      }

      // Prevent duplicates
      const existingIssue = await checkForDuplicateIssue(context, parsed.title)
      if (existingIssue) {
        context.log(`Duplicate issue found with title [${parsed.title}]`)
        await reopenClosed({ context, config, issue: existingIssue }, parsed)
        continue
      }

      let body = issue(context.repo({
        sha: parsed.sha,
        assignedToString: parsed.assignedToString,
        range: parsed.range,
        filename: parsed.filename,
        keyword: parsed.keyword,
        body: parsed.body
      }))

      body = lineBreak(body)
      context.log(`Creating issue [${parsed.title}] in [${context.repo().owner}/${context.repo().repo}]`)
      await context.github.issues.create(context.repo({ title: parsed.title, body, labels, ...assignFlow(config, parsed.username) }))
    }
  }
}

@@ -246,58 +246,8 @@
 f')%0A
-const parseChunk = require('./utils/parse-chunk')%0A
 cons
@@ -437,16 +437,81 @@
 r-body')
+%0Aconst shouldExcludeFile = require('./utils/should-exclude-file')
 %0A%0Amodule
@@ -1035,564 +1035,100 @@
 %0A%0A  
-const keywords = Array.isArray(config.keyword) ? config.keyword : %5Bconfig.keyword%5D%0A  const TITLE_REG = new RegExp(%60.+()%5C%5Cs(?%3Ckeyword%3E$%7Bkeywords.join('%7C')%7D)%5C%5Cs(?%3Ctitle%3E.*)%60)%0A  const excludePattern = config.exclude%0A%0A  let match%0A  for (const file of files) %7B%0A    if (file.to === '.github/config.yml') %7B%0A      context.log.debug('Skipping .github/config.yml')%0A      continue%0A    %7D else if (excludePattern && new RegExp(excludePattern).test(file.to)) %7B%0A      context.log.debug('Skipping ' + file.to + ' as it matches the exclude pattern ' + excludePattern)%0A     
+for (const file of files) %7B%0A    if (shouldExcludeFile(context.log, file.to, config.exclude))
  con
@@ -1132,22 +1132,16 @@
 continue
-%0A    %7D
 %0A%0A    fo
@@ -1308,16 +1308,17 @@
 %5Bindex%5D%0A
+%0A
         
@@ -1337,17 +1337,13 @@
 s = 
-TITLE_REG
+regex
 .exe
@@ -1935,32 +1935,42 @@
      let body = 
+lineBreak(
 issue(context.re
@@ -2192,32 +2192,33 @@
 fig)%0A        %7D))
+)
 %0A%0A        await 
@@ -2362,1398 +2362,7 @@
 %0A  %7D
-%0A%0A  return%0A%0A  for (let i = 0; i %3C chunks.length; i++) %7B%0A    const chunk = chunks%5Bi%5D%0A%0A    while ((match = regex.exec(chunk)) !== null) %7B%0A      const parsed = parseChunk(%7B match, context, config %7D)%0A%0A      if (parsed.filename === '.github/config.yml') %7B%0A        context.log.debug('Skipping .github/config.yml')%0A        continue%0A      %7D else if (excludePattern && new RegExp(excludePattern).test(parsed.filename)) %7B%0A        context.log.debug('Skipping ' + parsed.filename + ' as it matches the exclude pattern ' + excludePattern)%0A        continue%0A      %7D%0A%0A      // Prevent duplicates%0A      const existingIssue = await checkForDuplicateIssue(context, parsed.title)%0A      if (existingIssue) %7B%0A        context.log(%60Duplicate issue found with title %5B$%7Bparsed.title%7D%5D%60)%0A        await reopenClosed(%7B context, config, issue: existingIssue %7D, parsed)%0A        continue%0A      %7D%0A%0A      let body = issue(context.repo(%7B%0A        sha: parsed.sha,%0A        assignedToString: parsed.assignedToString,%0A        range: parsed.range,%0A        filename: parsed.filename,%0A        keyword: parsed.keyword,%0A        body: parsed.body%0A      %7D))%0A%0A      body = lineBreak(body)%0A      context.log(%60Creating issue %5B$%7Bparsed.title%7D%5D in %5B$%7Bcontext.repo().owner%7D/$%7Bcontext.repo().repo%7D%5D%60)%0A      await context.github.issues.create(context.repo(%7B title: parsed.title, body, labels, ...assignFlow(config, parsed.username) %7D))%0A    %7D%0A  %7D
 %0A%7D%0A

Remove old code