"use strict";
/**
 * @adonisjs/session
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileDriver = void 0;
/// <reference path="../../adonis-typings/index.ts" />
const path_1 = require("path");
const utils_1 = require("@poppinss/utils");
const helpers_1 = require("@poppinss/utils/build/helpers");
const fs_extra_1 = require("fs-extra");
/**
 * File driver to read/write session to filesystem
 */
class FileDriver {
    constructor(config) {
        this.config = config;
        if (!this.config.file || !this.config.file.location) {
            throw new utils_1.Exception('Missing "file.location" for session file driver inside "config/session" file', 500, 'E_INVALID_SESSION_DRIVER_CONFIG');
        }
    }
    /**
     * Returns complete path to the session file
     */
    getFilePath(sessionId) {
        return (0, path_1.join)(this.config.file.location, `${sessionId}.txt`);
    }
    /**
     * Returns file contents. A new file will be created if it's
     * missing.
     */
    async read(sessionId) {
        const filePath = this.getFilePath(sessionId);
        await (0, fs_extra_1.ensureFile)(filePath);
        const contents = await (0, fs_extra_1.readFile)(filePath, 'utf-8');
        if (!contents.trim()) {
            return null;
        }
        /**
         * Verify contents with the session id and return them as an object.
         */
        const verifiedContents = new helpers_1.MessageBuilder().verify(contents.trim(), sessionId);
        if (typeof verifiedContents !== 'object') {
            return null;
        }
        return verifiedContents;
    }
    /**
     * Write session values to a file
     */
    async write(sessionId, values) {
        if (typeof values !== 'object') {
            throw new Error('Session file driver expects an object of values');
        }
        const message = new helpers_1.MessageBuilder().build(values, undefined, sessionId);
        await (0, fs_extra_1.outputFile)(this.getFilePath(sessionId), message);
    }
    /**
     * Cleanup session file by removing it
     */
    async destroy(sessionId) {
        await (0, fs_extra_1.remove)(this.getFilePath(sessionId));
    }
    /**
     * Writes the value by reading it from the store
     */
    async touch(sessionId) {
        const value = await this.read(sessionId);
        if (!value) {
            return;
        }
        await this.write(sessionId, value);
    }
}
exports.FileDriver = FileDriver;
