/*
 *  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.
 *
 * Img0ch.Thread
 * $Id$
 *
 * @require jquery.js
 * @require img0ch/app.js
 */

var Img0ch;
if ( typeof Img0ch == "undefined" ) Img0ch = {};

Img0ch.Thread = function(app) {
    var app_  = app;
    var bbs_  = app_.getBBS();
    var key_  = app_.getKey();
    var path_ = app_.getBBSURI() + "/dat/" + key_ + ".dat.utf8";
    var res_  = [];
    var size_ = 0;
    var subject_;

    return {
    "count": function() { return res_.length },
    "flush": function() {
        res_.length = 0;
        size_       = 0;
        return;
    },
    "get": function(i) {
        return ( i < 1 || i > res_.length )
            ? [ "", "", "", "" ] : res_[ i - 1 ];
    },
    "getAll": function() { return res_ },
    "getBBS": function() { return bbs_ },
    "getDatURL": function() { return path_ },
    "getKey": function() { return key_ },
    "getSize": function() { return size_ },
    "getSubject": function() { return subject_ },
    "request": function(callback) {
        var self = this;
        jQuery.ajax({
            "url": path_,
            "ifModified": true,
            "global": false,
            "beforeSend": function(xml) {
                if ( size_ > 0 ) {
                    var from = "bytes=" + String(size_) + "-";
                    xml.setRequestHeader( "Range", from );
                }
                callback.initialize(xml);
            },
            "complete": function(xml) {
                var httpStatus = xml.status;
                var size       = 0;
                try {
                    size = xml.getResponseHeader("Content-Length");
                    if (isNaN(size)) size = app_.intval(xml.responseText.length);
                } catch(e) {
                    size = 0;
                }
                if ( httpStatus == 200 ) {
                    self.flush();
                    var dat = xml.responseText;
                    var res = dat.split("\n");
                    var len = res.length - 1;
                    res.length = len;
                    for ( var i in res ) {
                        if (isNaN(i)) continue;
                        res_.push(res[i].split("<>"));
                    }
                    subject_ = res_[0][4];
                    size_ += size;
                    callback.requestFirst();
                }
                else if ( httpStatus == 206 ) {
                    var start = res_.length;
                    var dat   = xml.responseText;
                    var res   = dat.split("\n");
                    var len   = res.length - 1;
                    res.length = len;
                    for ( var i in res ) {
                        if (isNaN(i)) continue;
                        res_.push(res[i].split("<>"));
                    }
                    size_ += size;
                    callback.requestModified( start, len );
                }
                else if ( httpStatus == 304 ) {
                    callback.requestNotModified();
                }
                else if ( httpStatus == 404 ) {
                    self.flush();
                    callback.requestNotFound();
                }
                else if ( httpStatus == 416 ) {
                    callback.requestNotSatisfied();
                    return;
                }
                else {
                    self.flush();
                    callback.requestOtherError( httpStatus, xml );
                }
                callback.requestComplete();
            }
            });
        return;
    },
    "search": function( searchType, searchWords, callback ) {
        if ( searchType < 0 || searchType > 3 ) searchType = 3;
        var found = 0;
        var wlen  = searchWords.length;
        callback.initialize();
        for ( var i in res_ ) {
            var res    = res_[i];
            if ( typeof res[3] == "undefined" ) continue;
            var hit    = 0;
            var resno  = Number(i) + 1;
            var result = [ res[0], res[1], res[2], res[3] ];
            var src    = res[searchType];
            for ( var j in searchWords ) {
                var word = searchWords[j];
                if ( src.indexOf(word) >= 0 ) {
                    src = callback.found( word, src );
                    hit++;
                }
            }
            if ( hit === wlen ) {
                found++;
                result[searchType] = src;
                callback.render( resno, result );
            }
        }
        callback.complete(found);
    }
    };
};
