/*
 *
 * @copyright Copyright (c) OX Software GmbH, Germany <info@open-xchange.com>
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with OX App Suite. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
 *
 * Any use of the work other than as authorized under this license or copyright law is prohibited.
 *
 */

import path from 'path'

// Do not use this for encryption (crypto.subtle.digest etc would be overkill for this)
export function hash (array) {
  const string = JSON.stringify(array)
  if (!string.length) throw new Error('TypeError: Unexpected data to calculate hash from')

  let hash = 0
  let char

  for (let i = 0; i < string.length; i++) {
    char = string.charCodeAt(i)
    hash = ((hash << 5) - hash) + char
    hash |= 0
  }

  return new Uint32Array([hash]).toString()
}

export function viteManifestToDeps (viteManifest) {
  const deps = {}
  for (const [codePoint, { isEntry, file, imports, css, assets }] of Object.entries(viteManifest)) {
    if (isEntry && codePoint.endsWith('.html')) deps[codePoint] = [file]
    if (Array.isArray(assets)) assets.forEach(asset => { deps[asset] = [] })
    if (Array.isArray(css)) css.forEach(css => { deps[css] = [] })
    deps[file] = []
      .concat(imports?.map(path => viteManifest[path].file))
      .concat(css)
      .concat(assets)
      .filter(Boolean)
  }
  return deps
}

export function viteToOxManifest (viteManifests) {
  const deps = viteManifestToDeps(viteManifests)
  return Object.values(viteManifests)
    .filter(manifest => Array.isArray(manifest?.meta?.manifests))
    .map(manifest =>
      manifest.meta.manifests.map(oxManifest => {
        const dependencies = deps[manifest.file]
        const data = {
          ...oxManifest,
          path: manifest.file.slice(0, -path.parse(manifest.file).ext.length)
        }
        if (dependencies?.length > 0) data.dependencies = dependencies
        return data
      })
    )
    .flat()
}

export function getRedisKey ({ version = undefined, name }) {
  if (version && name) return `${process.env.REDIS_PREFIX}:${version}:${name}`
  return `${process.env.REDIS_PREFIX}:${name}`
}

export function asyncThrottle (fn, context) {
  let next = null
  let current = null

  const wrapper = async function () {
    const result = await fn.apply(context || this, arguments)
    current = null
    if (next) current = next()
    next = null
    return result
  }

  return function () {
    if (current) {
      next = wrapper.bind(this, ...arguments)
      return current
    }
    return (current = wrapper.apply(this || context, arguments))
  }
}