function ListSearch(listValue,sID){
    
    for(var i = 0; i < listValue.length;i++){
        if(listValue[i].id == sID){
            return i;
        }
    }
    return -1;
}

function ContactDataBase(name){
    var CONTACT_NAME = "contact_" + name;
    this.listValue = [];

    this.insertContact = function( sDisplayName , sID){
        var value = {"name" : sDisplayName,'id':sID};
        
        var str = localStorage.getItem(CONTACT_NAME);
        if(str == null){
            this.listValue = [];
        }else{
            this.listValue  = JSON.parse(str);
        }
       
        this.listValue.push(value);

        str = JSON.stringify( this.listValue);
        localStorage.setItem(CONTACT_NAME,str);
    };

    this.removeContact = function(sID){
        var str = localStorage.getItem(CONTACT_NAME);
        this.listValue = JSON.parse(str);

        var i = ListSearch(this.listValue,sID);
        if(i >=0 ){
            this.listValue.splice(i,1);
        }

        str = JSON.stringify( this.listValue);
        localStorage.setItem(CONTACT_NAME,str);
    };
    this.removeContactList = function(arr){
        if(arr == null){
            return;
        }

        var str = localStorage.getItem(CONTACT_NAME);
        this.listValue = JSON.parse(str);

        for(var i = 0; i<arr.length;i++ ){
            var j = ListSearch(this.listValue,arr[i]);
            if(j >=0 ){
                this.listValue.splice(j,1);
            }
        }

        str = JSON.stringify( this.listValue);
        localStorage.setItem(CONTACT_NAME,str);
    };

    this.updateContact = function(sID,sDisplayName){

    };

    this.readContact = function(sID){
        var str = localStorage.getItem(CONTACT_NAME);
        this.listValue = JSON.parse(str);

        var i = ListSearch(this.listValue,sID);
        if(i >=0 ){
            return this.listValue[i];
        }
    };

    this.readContacts = function() {
        var str = localStorage.getItem(CONTACT_NAME);
        if(str == null || typeof str == 'undefined' || str.length == 0){
            this.listValue = [];
        }else{
            this.listValue = JSON.parse(str);
        }
        
        return this.listValue;
    };
}

module.exports = ContactDataBase;