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

Zeromin.User = function(id, bbs, key) {
    this.bbsID    = id  || 0;
    this.bbsDir   = bbs || '';
    this.cache = [];
    this.index = {};
}

Zeromin.User.prototype = {
    "getID": function () { return this.bbsID },
    "getBBS": function () { return this.bbsDir },
    "getCache": function () { return this.cache; },
    "setCache": function (cache, add) {
        add ? this.cache.push(cache) : this.cache = cache;
        return this;
    },
    "setIndex": function (key, i) {
        this.index[key] = i || this.cache.length;
    },
    "removeCache": function (data) {
        var count = 0;
        for ( var removedID in data ) {
            if ( !data[removedID] ) continue;
            var i = this.index[removedID];
            if ( i ) {
                delete this.index[removedID];
                this.cache.splice(i, 1);
                count++;
            }
        }
        return count;
    },
    "setBBS": function (id, bbs) {
        this.bbsID  = id;
        this.bbsDir = bbs;
        return this;
    },
    "get": function(id) {
        var cache = this.cache;
        var i     = this.index[id];
        return i ? cache[i]
            : { "id":    "",
                "name":  "",
                "mail":  "",
                "gname": ""
        };
    },
    "load": function (entriesByPage) {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("load"),
            function (storage) {
                var data = storage.read() || []
                var root = document.getElementById("userRoot");
                var ls = $(document.getElementById("userTable"));
                $("ul.nav-page", root).remove();
                ls.empty();
                for ( var i in data ) {
                    var item   = data[i];
                    var id     = item.id;
                    var tdBase = document.createElement("td");
                    tdBase.appendChild(
                        $(document.createElement("input")).attr({
                            "type" : "checkbox",
                            "name" : "id",
                            "value": id
                        }).get(0)
                    );
                    var lnk = $(document.createElement('a'));
                    lnk.href("javascript:Zeromin.getUser().setBBS("
                        + self.getID() + ",\"" + self.getBBS()
                        + "\").editForm(\"" + id + "\")");
                    lnk.append(document.createTextNode(item.name));
                    var tdName = document.createElement("td");
                    tdName.appendChild(lnk.get(0));
                    var tdMail = document.createElement("td");
                    tdMail.appendChild(
                        document.createTextNode(item.mail)
                    );
                    var tdGroup = document.createElement("td");
                    tdGroup.appendChild(
                        document.createTextNode(item.gname)
                    );
                    var trBase = document.createElement("tr");
                    trBase.appendChild(tdBase);
                    trBase.appendChild(tdName);
                    trBase.appendChild(tdMail);
                    trBase.appendChild(tdGroup);
                    ls.append(trBase);
                    self.setIndex(id, i);
                }
                Zeromin.DOM.makePager(ls.parent(),
                    (Zeromin.intval(entriesByPage) || 15));
                Zeromin.DOM.renderLeftMenu("leftUserMenu");
                Zeromin.DOM.toggleMenu("global");
                Zeromin.DOM.setFunction("USER - list");
                Zeromin.DOM.statusOK("ユーザー一覧を表示しました", 1000);
                $(".Container", document).hide();
                $(root).show();
            },
            this
        );
    },
    "save": function () {
        var self  = this;
        var param = this.toParam("save",
                        document.getElementById("userForm"));
        var user  = Zeromin.DOM.deserialize(param);
        Zeromin.getIO().load(
            param,
            function (storage) {
                var message;
                if ( storage.isReturnedSuccess() ) {
                    var id = storage.get("id");
                    if ( id != null ) {
                        message = "ユーザーアカウントを作成しました";
                    }
                    else {
                        id = user.id;
                        var removeFrom = new Object();
                        removeFrom[id] = true;
                        self.removeCache(removeFrom);
                        message = "ユーザーアカウントを編集しました";
                    }
                    self.setCache({
                        "id":    id,
                        "name":  user.name,
                        "mail":  user.mail,
                        "gname": Zeromin.getUgroup().getName(user.group)
                    }, true);
                    self.setIndex(id);
                }
                storage.writeStatus(
                    message, {
                        "2": "ユーザー名がありません",
                        "3": "メールアドレスが設定されていません",
                        "4": "ユーザーグループが設定されていません",
                        "5": "ユーザーのパスワードが設定されていません",
                        "6": "ユーザーの確認用パスワードが設定されていません",
                        "7": "メールアドレスの形式が不正です",
                        "8": "ユーザーのパスワードと確認用パスワードが一致しません",
                        "9": "存在しないユーザーグループが設定されています"
                    }
                );
            },
            null
        );
    },
    "remove": function () {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("remove", document.getElementById("userTable")),
            function (storage) {
                var removed = storage.get("removed");
                if ( removed == null ) {
                    Zeromin.DOM.statusNG("指定された処理は実行されませんでした");
                    return;
                }
                else {
                    self.removeCache(removed);
                    storage.writeStatus("指定されたユーザーアカウントを削除しました");
                }
            },
            null
        );
    },
    "editForm": function(id) {
        var item = this.get(id);
        var root = document.getElementById("userForm");
        Zeromin.DOM.fillForm(root, item, {
            "select-one-callback": function ( item, element ) {
                var val = item["gid"];
                var opt = element.options;
                var len = opt.length;
                for (var i = 0; i < len; i++) {
                    var o      = opt[i];
                    o.selected = (o.value == val ? true : false);
                }
            }
        });
        this.render("edit");
    },
    "render": function (renderType) {
        Zeromin.getUgroup().renderSelectBox();
        Zeromin.DOM.renderLeftMenu("leftUserMenu");
        Zeromin.DOM.toggleMenu("global");
        $(".Container", document).hide();
        switch (renderType) {
            case "create":
            default:
            var uf = document.getElementById("userForm");
            Zeromin.DOM.resetForm(uf);
            Zeromin.DOM.setFunction("USER - create");
            break;
            case "edit":
            Zeromin.DOM.setFunction("USER - edit");
            break;
        }
        $(document.getElementById("userForm")).show();
    },
    "toParam": function (meth, query) {
        var a = (query != null) ? $(query).fastSerialize() : [];
        a.push({ "name": "C",    "value": "user"       });
        a.push({ "name": "M",    "value": meth         });
        a.push({ "name": "type", "value": "individual" });
        return a;
    },
    "toString": function() { return "" }
};
