/*
 *  Copyright 2007 hkrn <hikarin@users.sourceforge.jp>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * Zeromin.Archive
 * $Id: archive.js 79 2007-01-11 12:25:09Z hikarin $
 */

Zeromin.Archive = function(bbs) {
    this.bbsID  = bbs.getID();
    this.bbsDir = bbs.getBBS();
    this.cache  = [];
    this.index  = {};
    this.loaded = false;
}

Zeromin.Archive.prototype = {
    "getID": function () { this.bbsID },
    "getBBS": function () { this.bbsDir },
    "getCache": function () { return this.cache; },
    "setCache": function (cache) {
        this.cache = cache;
        return this;
    },
    "setBBS": function (id, bbs) {
        if ( this.bbsDir != bbs ) {
            this.bbsID        = id;
            this.bbsDir       = bbs;
            this.index        = {};
            this.cache.length = 0;
        }
        return this;
    },
    "setIndex": function (key, i) {
        this.index[key] = i || this.cache.length - 1;
    },
    "addCache": function (data) {
        if ( !this.loaded ) return;
        var key = data.key;
        var i   = this.index[key];
        if ( !i ) {
            this.cache.push(data);
            this.setIndex(key);
        }
        return;
    },
    "removeCache": function (keys) {
        if ( !this.loaded ) return;
        var count = 0;
        for ( var key in keys ) {
            if ( !keys[key] ) continue;
            var i = this.index[key];
            if ( i ) {
                delete this.index[key];
                this.cache.splice(i, 1);
                count++;
            }
        }
        return count;
    },
    "get": function (key)  {
        var i = this.index[key];
        return i ? this.cache[i] : { "key": "", "subject": "", "count": 0 };
    },
    "load": function (entriesByPage) {
        var self = this;
        if ( !Zeromin.getArchive() ) {
            var archive = new Zeromin.Archive(this.bbsID, this.bbsDir, 0);
            Zeromin.setInstance("Archive", archive);
        }
        Zeromin.getIO().load(
            [
                { "name" : "C",    "value": "bbs"     },
                { "name" : "M",    "value": "load"    },
                { "name" : "type", "value": "archive" },
                { "name" : "bbs",  "value": this.bbsID   }
            ],
            function (storage) {
                var data = storage.slurp() || [];
                var root = document.getElementById("archiveRoot");
                var ls   = $(document.getElementById("archiveTable")).empty();
                $("ul.nav-page", root).remove();
                for ( var i in data ) {
                    var item    = data[i];
                    var key     = item.key;
                    var subject = item.subject;
                    var count   = item.count;
                    var tdBase  = document.createElement("td");
                    tdBase.appendChild(
                        $(document.createElement("input")).attr({
                            "type" : "checkbox",
                            "name" : "key",
                            "value": key
                        }).get(0)
                    );
                    var tdArchive = document.createElement("td");
                    tdArchive.appendChild(
                        document.createTextNode(subject)
                    );
                    var tdKey = document.createElement("td");
                    tdKey.title = Zeromin.getDate(key);
                    tdKey.appendChild(
                        document.createTextNode(String(key))
                    );
                    var tdCount = document.createElement("td");
                    tdCount.appendChild(
                        document.createTextNode(String(count))
                    );
                    var trBase = document.createElement("tr");
                    trBase.appendChild(tdBase);
                    trBase.appendChild(tdArchive);
                    trBase.appendChild(tdKey);
                    trBase.appendChild(tdCount);
                    ls.append(trBase);
                    self.setIndex(key, i);
                    self.loaded = true;
                }
                Zeromin.DOM.makePager(ls.parent(),
                    (Zeromin.intval(entriesByPage) || 15));
                Zeromin.DOM.toggleMenu("bbs");
                Zeromin.DOM.renderLeftMenu("leftArchiveMenu");
                Zeromin.DOM.setFunction(
                    "ARCHIVE - " + Zeromin.getBBS().getName()
                );
                Zeromin.DOM.statusOK("過去ログ一覧を表示しました", 1000);
                $(".Container", document).hide();
                $(root).show();
            },
            this
        );
    },
    "render": function() {
    },
    "sendCommand": function(o) {
        var self           = this;
        var selectedMethod = (typeof o == String ? o : o.value);
        if (selectedMethod == "null") return;
        else if (selectedMethod == "remove") {
            var message = "削除すると二度と復活することが出来なくなります。\n"
                        + "指定された過去ログを削除しますか？";
            if (confirm(message) == false) return;
        }
        Zeromin.DOM.disableMethodSelector();
        Zeromin.getIO().load(
            this.toParam(selectedMethod,
                document.getElementById("archiveRoot")),
            function (storage) {
                var removed;
                storage.writeResult(
                    selectedMethod, {
                         "update": "過去ログ一覧を更新しました",
                         "remove": "指定された過去ログを削除しました"
                    }
                );
                if ( selectedMethod == "remove" ) {
                    self.removeCache(storage.get("done"));
                }
                Zeromin.DOM.enableMethodSelector();
            },
            null
        );
    },
    "toParam": function (meth, query) {
        var a = (query != null) ? $(query).fastSerialize() : [];
        a.push({ "name": "bbs", "value": this.bbsID });
        a.push({ "name": "C",   "value": "archive"  });
        a.push({ "name": "M",   "value": meth       });
        return a;
    },
    "toString": function() { return this.getBBS() }
};
