/* @flow */

import path from 'path'
import invariant from 'invariant'
import fs from '../../util/fs'
import {Navy} from '../../navy'

import type {ConfigProvider} from '../../config-provider'
import type {State} from '../../navy'

export default function createFileSystemConfigProvider(navy: Navy): ConfigProvider {
  return {
    async getNavyPath(): Promise<string> {
      const envState: ?State = await navy.getState()

      invariant(!!envState, 'STATE_NONEXISTANT', navy.name)
      invariant(!!envState.path, 'FILESYSTEM_PROVIDER_REQUIRES_PATH', navy.name)

      try {
        await fs.statAsync(envState.path)
      } catch (ex) {
        invariant(false, 'FILESYSTEM_PROVIDER_INVALID_PATH', navy.name)
      }

      return envState.path
    },

    async getNavyFilePath(): Promise<string> {
      return path.join(await this.getNavyPath(), 'Navyfile.js')
    },

    async refreshConfig(): Promise<bool> {
      // no-op
      return false
    },

    async getLocationDisplayName(): Promise<string> {
      const envState: ?State = await navy.getState()

      invariant(!!envState, 'STATE_NONEXISTANT', navy.name)

      return envState.path
    },

    async isDangling(): Promise<boolean> {
      const envState: ?State = await navy.getState()

      if (!envState || !envState.path) {
        return true
      }

      try {
        await fs.statAsync(envState.path)
      } catch (ex) {
        return true
      }

      return false
    },
  }
}

createFileSystemConfigProvider.importCliOptions = []

createFileSystemConfigProvider.getImportOptionsForCLI = (opts) => {
  return {
    configProvider: 'filesystem',
    path: process.cwd(),
  }
}

@@ -126,16 +126,64 @@
 ../navy'
+%0Aimport %7BexecAsync%7D from '../../util/exec-async'
 %0A%0Aimport
@@ -273,16 +273,210 @@
 /navy'%0A%0A
+async function cwdHasValidDockerComposeConfig() %7B%0A  try %7B%0A    await execAsync('docker-compose', %5B'config'%5D, null, %7B cwd: process.cwd() %7D)%0A  %7D catch (ex) %7B%0A    return false%0A  %7D%0A%0A  return true%0A%7D%0A%0A
 export d
@@ -1814,16 +1814,22 @@
 ForCLI =
+ async
  (opts) 
@@ -1833,16 +1833,150 @@
 s) =%3E %7B%0A
+  const hasValidComposeConfig = await cwdHasValidDockerComposeConfig()%0A%0A  invariant(hasValidComposeConfig, 'NO_DOCKER_COMPOSE_FILE')%0A%0A
   return

Throw error when importing from filesystem when no compose file exists