/*
 *  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.Subject
 * $Id: subject.js 79 2007-01-11 12:25:09Z hikarin $
 */

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

Zeromin.Subject.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) {
        var key = data.key;
        var i   = this.index[key];
        if ( !i ) {
            this.cache.push(data);
            this.setIndex(key);
        }
        return;
    },
    "removeCache": function (keys) {
        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.getThread() ) {
            var thread = new Zeromin.Thread(this.bbsID, this.bbsDir, 0);
            Zeromin.setInstance("Thread", thread);
        }
        Zeromin.getIO().load(
            [
                { "name" : "C",    "value": "bbs"     },
                { "name" : "M",    "value": "load"    },
                { "name" : "type", "value": "subject" },
                { "name" : "bbs",  "value": this.bbsID   }
            ],
            function (storage) {
                var data = storage.slurp() || [];
                var root = document.getElementById("subjectRoot");
                var ls   = $(document.getElementById("subjectTable")).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 lnk = $(document.createElement('a'));
                    lnk.href(
                        "javascript:Zeromin.getThread().setBBS("
                        + self.bbsID + ", \"" + self.bbsDir + "\")"
                        + ".setKey(" + key + ").load()"
                    );
                    lnk.append(document.createTextNode(subject));
                    var tdSubject = document.createElement("td");
                    tdSubject.appendChild(lnk.get(0));
                    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(tdSubject);
                    trBase.appendChild(tdKey);
                    trBase.appendChild(tdCount);
                    ls.append(trBase);
                    self.setIndex(key, i);
                }
                var ent = entriesByPage || 15;
                Zeromin.DOM.makePager(ls.parent(),
                    (Zeromin.intval(entriesByPage) || 15));
                Zeromin.DOM.toggleMenu("bbs");
                Zeromin.DOM.renderLeftMenu("leftSubjectMenu");
                Zeromin.DOM.setFunction(
                    "SUBJECT - " + Zeromin.getBBS().getName()
                );
                Zeromin.DOM.statusOK("スレッド一覧を表示しました", 1000);
                $(".Container", document).hide();
                $(root).show();
            },
            this
        );
    },
    "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("subjectRoot")),
            function (storage) {
                var removed;
                storage.writeResult(
                    selectedMethod, {
                         "stop": "指定されたスレッドを停止しました",
                         "restart": "指定されたスレッドを再開しました",
                         "pool": "指定されたスレッドをプーリングしました",
                         "remove": "指定されたスレッドを削除しました"
                    }
                );
                // スレッド削除
                if ( removed = storage.get("removed") ) {
                    self.removeCache(removed);
                }
                // スレッドプーリング
                else if ( pooled = storage.get("done") ) {
                    var pool  = Zeromin.getBBS().getPool();
                    for ( var i in pooled ) {
                        pool.addCache(self.get(i));
                    }
                    self.removeCache(pooled);
                }
                Zeromin.DOM.enableMethodSelector();
            },
            null
        );
    },
    "doExport": function() {
    },
    "doImport": function() {
        $( "input[@name='bbs']",
            document.getElementById("threadImportForm") ).val(this.bbsID);
        Zeromin.getIO().upload(
            "threadImportForm",
            function (storage) {
                storage.writeStatus(
                    "アップロードされたファイルを掲示板に取り込みました", {
                        "2": "ファイルがアップロードされていません",
                        "3":  "dat、zip、tar.gzのいずれかのファイルでアップロードしてください"
                    }
                );
            }
        );
    },
    "render": function(renderType) {
        Zeromin.DOM.renderLeftMenu("leftSubjectMenu");
        Zeromin.DOM.toggleMenu("bbs");
        $(".Container", document).hide();
        switch (renderType) {
            case "autopool":
            default:
            Zeromin.DOM.setFunction("SUBJECT - autopooling");
            $(document.getElementById("threadAPForm")).show();
            break;
            case "import":
            case "export":
            Zeromin.DOM.setFunction("SUBJECT - import &amp; export");
            $(document.getElementById("threadIXForm")).show();
            break;
        }
    },
    "toParam": function (meth, query) {
        var a = (query != null) ? $(query).fastSerialize() : [];
        a.push({ "name": "bbs", "value": this.bbsID });
        a.push({ "name": "C", "value": "thread" });
        if ( meth ) a.push({ "name": "M", "value": meth });
        return a;
    },
    "toString": function() { return this.bbsDir }
};
