/* @flow */

import path from 'path'

import File from '../File'
import Rule from '../Rule'
import State from '../State'

import type { Action, Command, CommandOptions, OptionsInterface, Phase } from '../types'

export default class BibToGls extends Rule {
  static parameterTypes: Array<Set<string>> = [
    new Set(['LaTeXAuxilary']),
    new Set(['ParsedLaTeXAuxilary'])
  ]
  static description: string = 'Runs bib2gls to process bibliography files (bib) when need is detected.'

  static async isApplicable (state: State, command: Command, phase: Phase, options: OptionsInterface, parameters: Array<File> = []): Promise<boolean> {
    return state.isGrandparentOf(parameters[0], parameters[1]) &&
      !!parameters[1].value && !!parameters[1].value.commands.includes('glsxtr@resource')
  }

  async initialize () {
    await this.getResolvedInputs([
      '$DIR_0/$NAME_0.glg-ParsedBibToGlsLog',
      '$FILEPATH_0'
    ])
  }

  async getFileActions (file: File): Promise<Array<Action>> {
    switch (file.type) {
      case 'ParsedBibToGlsLog':
        return ['updateDependencies']
      case 'LaTeXAuxilary':
        return ['run']
    }

    return []
  }

  constructCommand (): CommandOptions {
    const { dir, name } = path.parse(this.firstParameter.filePath)
    const args = ['bib2gls']

    // Only push the -d option if needed.
    if (dir) args.push('-d', dir)
    args.push(name)

    return {
      args,
      cd: '$ROOTDIR',
      severity: 'error',
      outputs: [
        '$DIR_0/$NAME_0.glg'
      ]
    }
  }
}

@@ -10,33 +10,8 @@
 */%0A%0A
-import path from 'path'%0A%0A
 impo
@@ -107,16 +107,18 @@
 pe %7B
+%0A 
  Action,
  Com
@@ -113,16 +113,18 @@
  Action,
+%0A 
  Command
@@ -124,16 +124,18 @@
 Command,
+%0A 
  Command
@@ -142,16 +142,18 @@
 Options,
+%0A 
  Options
@@ -166,15 +166,17 @@
 ace,
+%0A 
  Phase
- 
+%0A
 %7D fr
@@ -779,145 +779,8 @@
  %7D%0A%0A
-  async initialize () %7B%0A    await this.getResolvedInputs(%5B%0A      '$DIR_0/$NAME_0.glg-ParsedBibToGlsLog',%0A      '$FILEPATH_0'%0A    %5D)%0A  %7D%0A%0A
   as
@@ -1063,91 +1063,50 @@
 nst 
-%7B dir, name %7D = path.parse(this.firstParameter.filePath)%0A    const args = %5B'bib2gls
+args = %5B'bib2gls', '-t', '%7B%7B$NAME_0.gelg%7D%7D
 '%5D%0A%0A
@@ -1155,19 +1155,38 @@
     if (
-dir
+this.env.DIR_0 !== '.'
 ) args.p
@@ -1199,11 +1199,20 @@
 d', 
-dir
+'%7B%7B$DIR_0%7D%7D'
 )%0A  
@@ -1227,12 +1227,21 @@
 ush(
-name
+'%7B%7B$NAME_0%7D%7D'
 )%0A%0A 
@@ -1321,27 +1321,75 @@
     
-out
+in
 puts: %5B
-%0A        
+'$DIR_0/$NAME_0.gelg-ParsedBibToGlsLog'%5D,%0A      outputs: %5B
 '$DI
@@ -1405,18 +1405,12 @@
 _0.g
+e
 lg'
-%0A      
 %5D%0A  

Set inputs and outputs in ConstructCommand