import v4 from '../lib/uuid.js'
import { Certificate, ICertificate } from './ClientCertificate.js'
import { CertificateFileKind } from './kinds.js'
import { IFile, File } from './store/File.js'
import { Thing } from './Thing.js'

export interface ICertificateFile extends IFile {
  kind: typeof CertificateFileKind
}

export class CertificateFile extends File {
  override kind = CertificateFileKind

  static fromCertificate(
    certificate: ICertificate | Certificate,
    organization: string,
    owner?: string
  ): CertificateFile {
    const init: ICertificateFile = {
      kind: CertificateFileKind,
      key: certificate.key,
      organization,
      info: Thing.fromName(certificate.name).toJSON(),
      lastModified: { user: owner || '', time: 0, byMe: false },
      owner,
      parents: [],
      permissionIds: [],
      permissions: [],
    }
    return new CertificateFile(init)
  }

  /**
   * @param name The name to set.
   * @param owner The user id that is the owner of the file.
   */
  static override fromName(name: string, organization: string, owner?: string): CertificateFile {
    return super.fromName(name, organization, owner, CertificateFileKind) as CertificateFile
  }

  constructor(input?: string | ICertificateFile) {
    super()
    let init: ICertificateFile
    if (typeof input === 'string') {
      init = JSON.parse(input)
    } else if (typeof input === 'object') {
      init = input
    } else {
      init = {
        kind: CertificateFileKind,
        key: v4(),
        organization: '',
        info: Thing.fromName('').toJSON(),
        parents: [],
        permissionIds: [],
        permissions: [],
        lastModified: { user: '', time: 0, byMe: false },
      }
    }
    this.new(init)
  }

  override new(init: ICertificateFile): this {
    if (!CertificateFile.isCertificate(init)) {
      throw new Error(`Not a certificate file.`)
    }
    super.new(init)
    this.kind = CertificateFileKind
    return this
  }

  static isCertificate(input: unknown): boolean {
    const typed = input as ICertificateFile
    if (!input || typed.kind !== CertificateFileKind) {
      return false
    }
    return true
  }

  override toJSON(): ICertificateFile {
    const result: ICertificateFile = {
      ...super.toJSON(),
      kind: CertificateFileKind,
    }
    return result
  }
}
