(function () {
    'use strict';
    window.CStorage = getStorage();

    function getStorage () {
        function Storage () {
            if (typeof localStorage !== 'undefined') {
                this.storage = localStorage;
            }
        }

        Storage.prototype = {
            _call: function (func, error) {
                if (!this.storage) {
                    return helper.callFunc(error.bind(this));
                }
                return helper.callFunc(func.bind(this));
            },
            /**
             * @public get
             * @param {String} key 
             * @returns {Object}
             */
            get: function (key) {
                return this._call(
                    function () {
                        var data = this.storage.getItem(key);

                        if (data) {
                            return JSON.parse(data);
                        }

                        return {};
                    },
                    function () {
                        return {};
                    }
                );
            },

            /**
             * @public set
             * @param {String} key 
             * @param {any} data 
             * @returns {void}
             */
            set: function (key, data) {
                this._call(
                    function() {
                        var node = {
                            data: data,
                            date: Date.now()
                        };
        
                        this.storage.setItem(key, JSON.stringify(node));
                    }
                );
            },

            /**
             * @public remvoe
             * @param {String} key 
             * @returns {void}
             */
            remove: function (key) {
                this._call(
                    function() {
                        this.storage.removeItem(key);
                    }
                );
            },

            removeAll: function () {
                this._call(
                    function () {
                        this.storage.clear();
                    }
                );
            },

            getItems: function () {
                return this._call(
                    function () {
                        return Object.keys(this.storage);
                    },
                    function () {
                        return [];
                    }
                );
            }
        }

        return Storage;
    }
})();