/*
 *  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.Thread
 * $Id: thread.js 109 2007-01-20 12:49:14Z hikarin $
 */

Zeromin.Thread = function(id, bbs, key) {
    this.bbsID    = id;
    this.bbsDir   = bbs;
    this.key   = key;
    this.cache = null;
}

Zeromin.Thread.prototype = {
    "getID": function () { return this.bbsID },
    "getBBS": function () { return this.bbsDir },
    "getKey": function () { return this.key },
    "getSubject": function () { return this.subject },
    "getCache": function (resno) {
        return resno ? this.cache.content[resno - 1] : this.cache;
    },
    "setCache": function (cache, add) {
        add ? this.cache.content.unshift(cache) : this.cache = cache;
        return this;
    },
    "updateCache": function (resno, content) {
        this.cache.content[resno - 1] = content;
    },
    "setBBS": function (id, bbs) {
        Zeromin.getBBS().setBBS(id, bbs);
        Zeromin.getSubject().setBBS(id, bbs);
        if ( this.bbsDir != bbs ) {
            this.bbsID    = id;
            this.bbsDir   = bbs;
            this.cache = null;
        }
        return this;
    },
    "setKey": function (key) {
        if ( this.key != key ) {
            this.key   = key;
            this.cache = null;
        }
        return this;
    },
    "addCache": function (resno, data) {
        this.cache[resno] = data;
        return;
    },
    "removeCache": function (resno) {
        if ( resno < 0 || resno > this.cache.length ) return;
        this.cache.splice(resno, 1);
        return;
    },
    "load": function (entriesByPage) {
        var self = this;
        var proc = $("div.Process");
        var temp = proc.html();
        Zeromin.getIO().load(
            this.toParam("load", null, null),
            function (storage) {
                var data = storage.slurp() || [];
                var root = document.getElementById("threadRoot");
                var ls   = $(document.getElementById("threadTable")).empty();
                article = data.content;
                subject = self.subject = data.subject;
                $("ul.nav-page", root).remove();
                for ( var i in article ) {
                    var item    = article[i];
                    var resno   = item.resno;
                    var tdBase  = document.createElement("td");
                    tdBase.appendChild(
                        $(document.createElement("input")).attr({
                            "type" : "checkbox",
                            "name" : "resno",
                            "value": resno
                        }).get(0)
                    );
                    var dt = $(document.createElement("dt"));
                    dt.html(
                        resno + " <b>" + item.name + "</b> ["
                        + item.mail + ']' + item.date
                    );
                    var dd = $(document.createElement("dd"));
                    var serial = item.serial;
                    var info;
                    if (serial) {
                        info = "SERIAL: " + serial + '(' + item.ip + ')';
                    }
                    else {
                        info = "HOST: " + item.ip;
                    }
                    var content = item.message + "<p class='blue'>";
                    var serial = item.serial;
                    if ( serial ) {
                        content += serial + " (";
                    }
                    else {
                        var ip = item.ip || "127.0.0.1";
                        content += "<a href='javascript:void(0)' "
                            + "onclick='Zeromin.DOM.getRemoteHost"
                            + "(this, event, \"" + ip + "\")'>"
                            + ip + "</a> (";
                    }
                    content += ( item.agent || "null" ) + ")</p>";
                    dd.id("r_" + resno).html(content).undblclick(
                        ).dblclick(function () {
                        var i = this.id.match(/\d+$/);
                        Zeromin.getThread().editForm(i);
                    });
                    var dl = document.createElement("dl");
                    dl.appendChild(dt.get(0));
                    dl.appendChild(dd.get(0));
                    var tdRes = document.createElement("td");
                    tdRes.appendChild(dl);
                    var trBase = document.createElement("tr");
                    trBase.appendChild(tdBase);
                    trBase.appendChild(tdRes);
                    ls.append(trBase);
                }
                proc.html(temp);
                ls.parent().pager(Zeromin.intval(entriesByPage) || 10);
                $(document.getElementById("threadSubject")).html(subject);
                Zeromin.DOM.toggleMenu("thread");
                Zeromin.DOM.renderLeftMenu("leftThreadMenu");
                Zeromin.DOM.setFunction(
                    "THREAD - " + Zeromin.getBBS().getName()
                    + " - " + subject
                );
                Zeromin.DOM.statusOK("「" + subject + "」を表示しました", 1000);
                $(".Container", document).hide();
                $(root).show();
            },
            this
        );
    },
    "save": function() {
        var self   = this;
        var param  = this.toParam("save",
                         document.getElementById("threadForm"));
        var thread = Zeromin.DOM.deserialize(param);
        Zeromin.getIO().load(
            param,
            function (storage) {
                if ( storage.isReturnedSuccess() ) {
                    var resno = thread.resno;
                    var r     = self.getCache(resno);
                    r.name    = thread.FROM;
                    r.mail    = thread.mail;
                    r.message = thread.MESSAGE.replace(/\n/g, "<br>");
                    self.updateCache(resno, r);
                }
                storage.writeStatus(
                    "指定されたレスの編集内容を保存しました", {}
                );
            },
            null
        );
    },
    "sendCommand": function(o) {
        var selectedMethod = (typeof o == String ? o : o.value);
        var removeType;
        if (selectedMethod == "null") return;
        switch ( selectedMethod ) {
            case "erase":
            removeType = "is_erase";
            break;
            case "removeFile":
            removeType = "is_file_only";
            break;
        }
        Zeromin.DOM.disableMethodSelector();
        Zeromin.getIO().load(
            this.toParam(
                "remove",
                document.getElementById("threadRoot"),
                removeType
            ),
            function (storage) {
                storage.writeResult(
                    selectedMethod, {
                         "replace": "指定されたレスを削除(あぼーん)しました",
                         "erase": "指定されたレスを透明削除(透明あぼーん)しました",
                         "removeFile": "指定されたレスのファイルを削除しました"
                    }
                );
                Zeromin.DOM.enableMethodSelector();
            },
            null
        );
    },
    "editForm": function (resno) {
        var item = this.getCache(resno);
        if ( item != null ) {
            var tform = document.getElementById("threadForm");
            $("input[@name='FROM']", tform).val(item.name);
            $("input[@name='mail']", tform).val(item.mail);
            $("input[@name='resno']", tform).val(resno);
            $("textarea[@name='MESSAGE']", tform).val(
                item.message.replace(/^\s/,
                    "").replace(/\s*<br\s?\/?>\s/g,
                    "\n").replace(/\s$/, "")
            );
            $("span#articleDate", tform).html(
                Zeromin.DOM.escapeHTML(item.date));
            $(".Container", document).hide();
            $(tform).show();
        }
        else {
            Zeromin.DOM.statusNG(resno + "番のレスは存在しません");
        }
    },
    "getLogError": function (id, bbs, key, entriesByPage) {
        var logError = Zeromin.getLogError();
        if ( !logError ) {
            logError = new Zeromin.Log.Error(this);
            Zeromin.setInstance("Log.Error", logError);
        }
        if ( id && bbs ) {
            this.bbsID  = id;
            this.bbsDir = bbs;
            logError.setBBS(id, bbs);
        }
        else {
            logError.setBBS(this.bbsID, this.bbsDir);
        }
        if ( key ) {
            this.key = key;
            logError.setKey(key);
        }
        else {
            logError.setKey(this.key);
        }
        return entriesByPage ? logError.load(entriesByPage) : logError;
    },
    "getPlugin": function (id, bbs, key, entriesByPage) {
        var plugin = Zeromin.getPlugin();
        if ( !plugin ) {
            plugin = new Zeromin.Plugin(this);
            Zeromin.setInstance("Plugin", plugin);
        }
        if ( id && bbs ) {
            this.bbsID  = id;
            this.bbsDir = bbs;
            plugin.setBBS(id, bbs);
        }
        else {
            plugin.setBBS(this.bbsID, this.bbsDir);
        }
        if ( key ) {
            this.key = key;
            plugin.setKey(key);
        }
        else {
            plugin.setKey(this.key);
        }
        return entriesByPage ? plugin.load(entriesByPage) : plugin;
    },
    "toParam": function (meth, query, removeType) {
        var a = (query != null) ? $(query).fastSerialize() : [];
        a.push({ "name": "bbs", "value": this.bbsID  });
        a.push({ "name": "key", "value": this.key });
        a.push({ "name": "C",   "value": "thread" });
        if ( meth ) a.push({ "name": "M", "value": meth });
        if ( removeType ) a.push({ "name": removeType, "value": 1 });
        return a;
    },
    "toString": function() { return this.getKey() }
};
