/**
 * 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 HashUtil = require('./hashutil'),
    oidParam = {};

var OidUtil = {
    setIp: function(ip){
        ip = ip.replace(/\./g, '-');
        var ips = ip.split('-');

        for(var i = 0 ; i < ips.length ; i++){
            oidParam['ip'+i] = ips[i];
        }
    },
    setPort: function(port){
        port = port || 0;
        oidParam['port'] = Number(port);
    },
    setPid: function(pid){
        oidParam['pid'] = Number(pid);
    },
    setHostName: function(hostName){
        oidParam['hostname'] = hostName;
    },
    setType: function(type){
        oidParam['type'] = type;
    },
    setCluster: function(cluster){
        oidParam['cluster'] = cluster;
    },
    setOkind: function(okind){
        oidParam['okind'] = okind;
    },
    setCmd: function(cmd){
        var cmds = [];
        if(!cmd || cmd.length < 1 ){
            cmds = [];
        }else{
            cmds = cmd.split(' ');
        }

        for(var i = 0 ; i < 10; i++){
            if(i < cmds.length){
                oidParam['cmd'+i] = cmds[i];
            }else{
                oidParam['cmd'+i] = '';
            }
        }
    },
    mkOid: function(oname){
        return HashUtil.hash(Buffer.from(oname));
    },
    mkOname: function(pattern, port){
        var conf = require('./../conf/configure');
        var startBrace = "{";
        var endBrace = "}";

        var regex = new RegExp('\\'+startBrace+'(.*?)\\'+endBrace,'g');
        var m;
        var keys = [];
        while ((m = regex.exec(pattern)) !== null) {
            if (m.index === regex.lastIndex) {
                regex.lastIndex++;
            }

            keys.push(m[1])
        }
        for(var i = 0 ; i < keys.length ; i ++){
            var key = keys[i],
                keyFull = startBrace + key + endBrace;

            if (conf.getProperty(key)) {
                pattern = pattern.replace(keyFull, conf.getProperty(key));
            } else if (process.env[key]) {
                pattern = pattern.replace(keyFull, process.env[key]);
            } else if( oidParam[key] ){
                pattern = pattern.replace(keyFull, oidParam[key]);
            }else{
                pattern = pattern.replace(keyFull, key);
            }
        };
        if(conf.getProperty('oname_port_postfix_enabled', false) && port){
            pattern = pattern + '-' + port;
        }
        return pattern;
    },
    toString: function(){
        var str = '';
        for(var k in oidParam){
            str += k+': '+oidParam[k]+'\n';
        }
        return str;
    }
};

module.exports = OidUtil;