import { noop } from "../utils";

export default function({ isEnabled, cookieName } = {}, { cookies } = {}) {
    if (!isEnabled || !cookieName || !cookies) {
        return {
            get: noop,
            set: noop,
            remove: noop
        };
    }

    return {
        remove: function() {
            cookies.remove(cookieName);
        },
        get: function() {
            var cookieValue = cookies.get(cookieName);
            var approvalsObj = {};

            try {
                // TODO Validate cookie content.
                approvalsObj = JSON.parse(cookieValue);
            } catch (ex) {
                // Fail gracefully and silently.
                approvalsObj = {};
            }
            return approvalsObj;
        },
        set: function(value, config) {
            // Serialize approvals.
            config = config || {};

            cookies.set(cookieName, JSON.stringify(value), {
                domain: config.optInCookieDomain || "",
                cookieLifetime: config.optInStorageExpiry || 34190000, // Default is 13 months in seconds
                expires: true
            });
        }
    };
}
