/**
 * Copyright 2016 the WHATAP project authors. All rights reserved.
 * Use of this source code is governed by a license that
 * can be found in the LICENSE file.
 */

var Value       = require('./value'),
    ValueEnum   = require('./valueenum'),
    IPUtil      = require('../util/iputil');

function IP4Value() {
    Value.call(this);
    this.value = new Array(4);

    this.compareTo = function(object) {
        if(object instanceof IP4Value) {
            if(object.value == null && this.value == null) {
                return 0;
            }
            if(this.value == null) {
                return -1;
            }
            if(object.value == null) {
                return 1;
            }
            var l_len = this.length,
                r_len = object.length;
            for(var i=0; i<l_len.length && i < r_len.length; i++) {
                if(this.value[i] > object.value[i]) {
                    return 1;
                }
                if(this.value[i] < object.value[i]) {
                    return -1;
                }
            }
            return l_len - r_len;
        }
        return 1;
    };
    this.equals = function(object) {
        if(object instanceof IP4Value) {
            return this.value === object.value;
        }
        return false;
    }
    this.hashCode = function() {
        if(this.value == null) {
            return 0;
        }
        var h=0;
        var len = this.value.length;
        for(var i = 0 ; i < len ; i++){
            h+=this.value[i];
        }
        return h;
    }
    this.toString = function() {
        return IPUtil.bytesToString(this.value);
    };
}

IP4Value.prototype = new Value();
IP4Value.prototype.constructor = IP4Value;
IP4Value.prototype.getValueType = function() {
    return ValueEnum.IP4ADDR;
};
IP4Value.prototype.write = function(dout) {
    if(this.value == null) {
        this.value = [0, 0, 0, 0];
    }
    dout.writeBytes(this.value);
};
IP4Value.prototype.read = function(din) {
    if(this.value == null) {
        this.value = [0, 0, 0, 0];
    }
    this.value = din.read(4);
    return this;
};
IP4Value.prototype.toObject = function() {
    return this.value;
};

module.exports = IP4Value;