import { useEvent } from "@aet/hooks"
import { gql, useLazyQuery } from "~/generated/graphql"
import { removeTypeName } from "~/shared/removeTypeName"
import { useDispatch } from "../store"
import { openFile } from "../store/actions"
import { SECTION_FRAGMENT } from "../fragments"

const GET_FILE = gql<"GetFile">`
  ${SECTION_FRAGMENT}
  query GetFile($id: ID!) {
    file(id: $id) {
      id
      tags
      rules {
        exclude
        type
        value
      }
      sections {
        ...SectionFragment
      }
    }
  }
`

export function useOpenFile() {
  const [query] = useLazyQuery(GET_FILE)
  const dispatch = useDispatch()

  return useEvent(async (id: string) => {
    const { data } = await query({ variables: { id } })
    dispatch(openFile(removeTypeName(data!.file)))
  })
}
