import { Arg, FieldResolver, ID, Mutation, Resolver, Root } from "@aet/gql-tools/macro"
import { statistics } from "../../idb"
import { File } from "~/shared/models"

@Resolver(() => File)
export class StatisticsResolver {
  @Mutation()
  async toggleDisableLogging(@Arg() fileId: ID, @Arg() value: boolean) {
    await statistics.update(fileId, data => ({ ...data, disableLogging: value }))
    return true
  }

  @Mutation()
  async resetUsageData(@Arg() fileId?: ID) {
    if (fileId == null) {
      await statistics.clear()
    } else {
      await statistics.update(fileId, data => ({ ...data, lastRequested: undefined }))
    }
    return true
  }

  @FieldResolver()
  disabledLogging(@Root() file: File): boolean {
    return isFileLoggingDisabled(file.id)
  }
}

export function isFileLoggingDisabled(fileId: ID) {
  return statistics.get(fileId)?.disableLogging || false
}
