import { IFile, File } from './store/File.js'
import { nanoid } from '../nanoid.js'
import { Thing } from './Thing.js'
import { FolderKind } from './kinds.js'

/**
 * A definition of a folder.
 */
export interface IFolder extends IFile {
  kind: typeof FolderKind
}

/**
 * A definition of a folder.
 */
export class Folder extends File {
  override kind = FolderKind

  /**
   * Creates a new Folder object from a name.
   *
   * @param name The name to set.
   */
  static override fromName(name: string): Folder {
    return super.fromName(name, FolderKind) as Folder
  }

  /**
   * @param input The environment definition used to restore the state.
   */
  constructor(input?: string | IFolder) {
    super()
    let init: IFolder
    if (typeof input === 'string') {
      init = JSON.parse(input)
    } else if (typeof input === 'object') {
      init = input
    } else {
      init = {
        kind: FolderKind,
        key: nanoid(),
        info: Thing.fromName('').toJSON(),
        parents: [],
        permissionIds: [],
        permissions: [],
        lastModified: { user: '', time: 0, byMe: false },
      }
    }
    this.new(init)
  }

  /**
   * Creates a new environment clearing anything that is so far defined.
   */
  override new(init: IFolder): this {
    if (!Folder.isFolder(init)) {
      throw new Error(`Not a folder.`)
    }
    super.new(init)
    this.kind = FolderKind
    return this
  }

  /**
   * Checks whether the input is a definition of a folder.
   */
  static isFolder(input: unknown): boolean {
    const typed = input as IFolder
    if (!input || typed.kind !== FolderKind) {
      return false
    }
    return true
  }

  override toJSON(): IFolder {
    const result: IFolder = {
      ...super.toJSON(),
      kind: FolderKind,
    }
    return result
  }
}
