"use strict";

/**
 * @typedef {import("../OpoTests.ecma.js").OpoTests} OpoTests
 */

import {Utils} from "../Utils/Utils.ecma.js";

/**
 * @class CookiesManager
 * @constructor
 * @param {!OpoTests} ot 
 * @returns {void}
 * @access public
 * @static
 */
export const CookiesManager = (function(){

    /**
     * @callback cookies_manager_default_callback
     * @returns {void}
     */

    /**
     * @constructs CookiesManager
     * @param {!OpoTests} ot 
     * @returns {void}
     * @access private
     * @static
     */
    const CookiesManager = function(ot){

        /** @type {CookiesManager} */
        const self = this;
        /** @type {number} */
        let timeout = 3600000;

        /**
         * @returns {void}
         * @access private
         */
        const constructor = () => {};

        /**
         * @param {?cookies_manager_default_callback} [callback = null] 
         * @return {void}
         * @access public
         */
        this.start = (callback = null) => {

            timeout = ot.settings.get(["cookies_timeout", "timeout"], null, timeout);

            Utils.execute(callback);

        };

        /**
         * @param {!string} name 
         * @returns {boolean}
         * @access public
         */
        this.has = name => {

            name += "=";

            return document.cookie.split(';').some(c => c.trim().startsWith(name));
        };

        /**
         * @param {!string} name 
         * @param {!string} value 
         * @returns {void}
         * @access public
         */
        this.set = (name, value) => {
            document.cookie = (
                name + "=" + (value || "") + ";" + 
                "expires=" + new Date(Date.now() + timeout).toUTCString() + ";" + 
                "path=/"
            );
        };

        /**
         * @param {!string} name 
         * @returns {?string}
         * @access public
         */
        this.get = name => {

            name += "=";

            for(const cookie of document.cookie.split(';'))
                if(cookie.trim().startsWith(name))
                    return cookie.trim().substring(name.length);
            return null;
        };

        /**
         * @param {!string} name 
         * @returns {void}
         * @access public
         */
        this.remove = name => {   
            self.has(name) && (document.cookie = name + "=; Max-Age=-99999999;");  
        };

        constructor();

    };

    return CookiesManager;
})();