// @flow
import * as Types from '../../constants/types/fs'
import * as Constants from '../../constants/fs'
import * as FsGen from '../fs-gen'
import type {TypedActions} from '../typed-actions-gen'

const makeErrorHandler = (action: FsGen.Actions, path: ?Types.Path, retriable: boolean) => (
  error: any
): Array<TypedActions> => {
  if (path) {
    // TODO: KBFS-4143 add and use proper error code for all these
    if (typeof error.desc === 'string') {
      if (
        error.desc.includes('does not have read access to') ||
        error.desc.includes('You are not a member of this team') ||
        // team doesn't exist
        error.desc.includes('Root team does not exist') ||
        // public tlf doesn't exist
        error.desc.includes("Can't create TLF ID for non-team-backed handle") ||
        // /keybase/private/non_existent_user
        error.desc.includes(' is not a Keybase user')
      ) {
        const tlfPath = Constants.getTlfPath(path)
        if (tlfPath) {
          return [FsGen.createSetTlfSoftError({path: tlfPath, softError: 'no-access'})]
        }
      }
      if (error.desc.includes('file does not exist')) {
        return [FsGen.createSetPathSoftError({path, softError: 'non-existent'})]
      }
    }
    if (error.desc.includes('KBFS client not found.')) {
      return [
        FsGen.createKbfsDaemonRpcStatusChanged({rpcStatus: 'wait-timeout'}),
        // We don't retry actions when re-connected, so just route user back
        // to root in case they get confused by orphan loading state.
        //
        // Although this seems impossible to do for nav2 as things are just
        // pushed on top of each other, so just don't do anything for now.
        // Perhaps it's OK.
      ]
    }
  }
  return [
    FsGen.createFsError({
      error: Constants.makeError({
        error,
        erroredAction: action,
        retriableAction: retriable ? action : undefined,
      }),
    }),
  ]
}

export const makeRetriableErrorHandler = (action: FsGen.Actions, path: ?Types.Path) =>
  makeErrorHandler(action, path, true)

export const makeUnretriableErrorHandler = (action: FsGen.Actions, path: ?Types.Path) =>
  makeErrorHandler(action, path, false)

@@ -1233,20 +1233,16 @@
     %7D%0A  
-  %7D%0A
     if (
@@ -1292,24 +1292,26 @@
 ')) %7B%0A      
+  
 return %5B%0A   
@@ -1303,24 +1303,26 @@
    return %5B%0A
+  
         FsGe
@@ -1394,16 +1394,18 @@
         
+  
 // We do
@@ -1465,16 +1465,18 @@
 er back%0A
+  
         
@@ -1545,16 +1545,18 @@
         
+  
 //%0A     
@@ -1558,16 +1558,18 @@
         
+ 
+ 
 // Altho
@@ -1632,24 +1632,26 @@
 ust%0A        
+  
 // pushed on
@@ -1713,16 +1713,18 @@
         
+ 
+ 
 // Perha
@@ -1741,17 +1741,27 @@
 .%0A      
-%5D
+  %5D%0A      %7D
 %0A    %7D%0A 

fix error parse bug