/**
 * @copyright Copyright (c) Open-Xchange 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 { asyncThrottle, hash } from '../src/util.js'
import { generateSimpleViteManifest, wait } from './util.js'
import { expect } from 'chai'
import sinon from 'sinon'

const sandbox = sinon.createSandbox()

describe('Util', function () {
  describe('hash function', function () {
    it('computes the hash', function () {
      const manifest = generateSimpleViteManifest({
        'example.js': { imports: ['test.css'] },
        'test.css': { }
      })
      expect(hash(manifest)).to.equal('2245696177')
    })

    it('the hash changes when the manifest changes', function () {
      const manifest = generateSimpleViteManifest({
        'example.js': { imports: ['test.css'] },
        'test.css': { }
      })
      const manifestChanged = generateSimpleViteManifest({
        'example.js': { imports: ['test1.css'] },
        'test1.css': { }
      })

      expect(hash(manifest)).not.to.equal(hash(manifestChanged))
      expect(hash(manifest)).to.equal('2245696177')
      expect(hash(manifestChanged)).to.equal('2547998666')
    })
  })

  describe('asyncThrottle function', function () {
    let spy

    beforeEach(function () {
      spy = sandbox.spy(function () {
        return new Promise((resolve, reject) => {
          // @ts-ignore
          spy.resolve = resolve
          // @ts-ignore
          spy.reject = resolve
        })
      })
    })

    it('works', function () {
      const throttled = asyncThrottle(spy)
      expect(spy.callCount).to.equal(0)
      throttled()
      expect(spy.callCount).to.equal(1)
    })

    it('is only called once again on the trailing edge', async function () {
      const throttled = asyncThrottle(spy)
      expect(spy.callCount).to.equal(0)
      throttled()
      expect(spy.callCount).to.equal(1)
      throttled()
      expect(spy.callCount).to.equal(1)
      spy.resolve()
      await wait(0)
      expect(spy.callCount).to.equal(2)
      spy.resolve()
      await wait(0)
      expect(spy.callCount).to.equal(2)
    })
  })
})