import { calculate as calculateHashes } from "./hashes.js";

window.HashesChecker = function( wire ) {
    return {

        /**
         * Wire variable instance.
         */
        $wire: wire,

        /**
         * If a file hash is currently calculated or not.
         * @type {boolean}
         */
        isCalculating: false,

        /**
         * An error on hash calculation.
         * @type {any|null}
         */
        error: null,

        async handleSubmitFile(e){
            if( this.isCalculating === true ) // Calculation already done for another file.
                return;

            this.error = null; // Reset.
            const FILE = e.target.files[0];

            if( !FILE )
                return; // No file sent.

            this.isCalculating = true;

            try {
                const RESULT = await calculateHashes(FILE);
                await this.$wire.addHash(RESULT.filename, RESULT.crc32, RESULT.sha1); // Send a signal to livewire.
                window.refreshIcons();
            } catch(err) {
                this.error = err.message;
            } finally {
                this.isCalculating = false;
            }
        }

    }
}
