/**
 * 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.
 */


function LinkedList() {
	this._length = 0;
	this._head = null;
	this._current = null;
	this._tail = null;
}

LinkedList.prototype = {
	size : function(){
		return this._length;
	},
	add : function(data) {
		var node = {
			data : data,
			next : null,
			prev: null
		};
		if (this._head == null) {
			this._head = node;
			this._current = {next: node};
		} else {
			this._tail.next = node;
			node.prev = this._tail;
		}
        this._tail = node;
		this._length++;
	},
	get : function(index) {
		if (index > -1 && index < this._length) {
			var current = this._head, i = 0;
			while (i++ < index) {
				current = current.next;
			}
			return current.data;
		} else {
			return null;
		}
	},
	remove : function(index) {
		if (index > -1 && index < this._length) {
			var current = this._head, previous, i = 0;
			if (index === 0) {
				this._head = current.next;
			} else {
				while (i++ < index) {
					previous = current;
					current = current.next;
				}
				previous.next = current.next;
			}
			this._length--;
			return current.data;
		} else {
			return null;
		}
	},
	getFirst : function() {
		return this._head.data;
	},
	getValue : function(ent) {
		if (ent == null)
			return null;
		return ent.data;
	},
	next : function() {
		if(this._current.next){
			this._current = this._current.next;
			return this._current.data;
		}else{
			return null;
		}
	},
	hasNext : function() {
        if(this._current && this._current.next){
            return true;
        } else{
            return false;
        }
    },
    removeFirst : function() {
        var target = this._head;
        if (this._head != null) {
            if(this._head === this._current.next){
            	delete this._current;
			}
			if(this._head.next){
                this._head = this._head.next;
                this._current = this._head;
                this._head.prev = null;
			}else{
				this._head = null;
			}
            this._length--;
        }
        return target.data;
    },
	removeEntry : function(current) {
		if (current == null)
			return;

		if (this._head === current) {
			this._head = current.next;
		} else {
			var previous = current;
			current = current.next;
			previous.next = current.next;
		}
		this._length--;
	},
	toString : function() {
		var str = "";
		var e = list.getFirst();
		if (e == null) {
			return "[]";
		} else {
			str = "[" + e.data;
			e = list.getNext(e);
		}
		while (e !== null) {
			str += "," + e.data;
			e = list.getNext(e);
		}
		return str + "]";
	}
};

module.exports = LinkedList;