//引入相关插件
const nodeOs    = require('os');
const net 		= require('net');

let myTools  = {
	version : '1.0.0',
	author  : 'rucky',
	print : function(){
		//打印基本信息
		this.nodeConsole({title:'操作系统',content:this.getSystem(),mode:4});
		this.nodeConsole({title:'版本',content:nodeOs.release(),mode:1});
		this.nodeConsole({title:'IP',content:this.getIP(),mode:1});
	},
	/**************************/
	/*****↓↓↓获取本地IP↓↓↓*****/
	/**************************/
	getIP : function(){  	
	    let interfaces = nodeOs.networkInterfaces();  	//通过node获取网络配置列表
		let IP = 'localhost';
		const ipArr = [];
	    for(let devName in interfaces){  
	          let iface = interfaces[devName];
	          for(let i=0;i<iface.length;i++){  
				   let alias = iface[i];
	               if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){	//已加入网络
						// return alias.address
					   ipArr.push(alias.address)
	               }
	          }  
		}
		if (ipArr.length === 1) {
			IP = ipArr[0]
		} else if (ipArr.length > 0) {
			ipArr.forEach((item,index) => {
				if(item.indexOf('192.168.1') > -1) {
					IP = item
				}else{
					IP = item;
				}
			})

			if (IP === 'localhost') {
				item = ipArr[0]
			}
		}

	    return IP;
	    // example data
		// [
		//    {
		//      address: 'fe80::f86b:2ce4:610e:cde1',
		//      netmask: 'ffff:ffff:ffff:ffff::',
		//      family: 'IPv6',
		//      mac: '64:00:6a:12:5c:03',
		//      scopeid: 3,
		//      internal: false
		//    }, 
		//    {
		//      address: '192.168.31.28',
		//      netmask: '255.255.255.0',
		//      family: 'IPv4',
		//      mac: '64:00:6a:12:5c:03',
		//      internal: false
		//    }
		//  ]	    
	},


	/**************************/
	/**↓↓↓检测端口是否被占用↓↓↓***/
	/**************************/
	portIsOccupied : function(port) {
		// 创建服务并监听该端口
		var server = net.createServer().listen(port)

		server.on('listening', function () { // 执行这块代码说明端口未被占用
			server.close() // 关闭服务
			// return false
			console.log('The port【' + port + '】 is available.') // 控制台输出信息
		})

		server.on('error', function (err) {
			if (err.code === 'EADDRINUSE') { // 端口已经被使用
				// return true
				console.log('The port【' + port + '】 is occupied, please change other port.')
			}
		})
	},

	/**************************/
	/***↓↓↓ 获取系统名称 ↓↓↓***/
	/**************************/	
	getSystem:function(){
		let system = nodeOs.platform();			//'darwin' mac, 'freebsd' UNIX, 'linux', 'sunos' sunos, 'win32' windows
	    let _name;
	    switch(system){
	        case 'win32':
	            _name = "windows";
	            break;
	        case 'linux':
	            _name = system;
	        break;        
	        case 'darwin':
	            _name = "mac";
	            break; 
	        default:
	            _name = "windows";
	            break;               
	    }
	    return _name;
	},
	/**************************/
	/***↓↓↓ node Console ↓↓↓***/
	/**************************/
	nodeConsole:function(param){
		let _default = {										// 标题
        	title:   'Rucky',
        	content: typeof param == 'string'? param : 'Lee',	// 内容 如果传入内容为字符串直接赋值给content
        	mode:    1,											// 1-*,2-=,3--,4-<>
        	maxLen:  27,										// 内容最大字节 默认左右各空4个 中间可描述字符19 默认gap / ** / 4个字符
        	betweenLen:17
    	};

        let opts = Object.assign({}, _default, param );

        

        let getLength = function(str) {
		  	return (str ? str : 'undefined').replace(/[\u0391-\uFFE5]/g,"aa").length;   //先把中文替换成两个字节的英文，在计算长度
		}

		let createSpaceStr = function(len,symbol){
			let placeholder = symbol ? symbol: ' ';
			let array       = [];
			for(let i       = 0 ; i < len ; i++ ){
				if(symbol == '>' && i > len/2)
					placeholder = Symbols[5]
				array.push(placeholder);
			}
			return array.join('');
		}

		let trueLen  = getLength(opts.title)+getLength(opts.content);

		let messageStr = '';
        let gap     = [];	//' ** '
        let extra   = opts.maxLen-trueLen;
        let startSpace,endSpace;
        let topSymbol,bottomSymbol;
        let Symbols = ['','*','=','-','>','<'];
        // console.error(trueLen)
        if(extra >= 0){
        	topSymbol = bottomSymbol = createSpaceStr(opts.maxLen+opts.betweenLen,Symbols[opts.mode]);
        	if(extra > 8){					//如果大于8空格 旁边则保留4空格
        		startSpace = endSpace = createSpaceStr(4);
        		// console.log(extra)
        		if(extra >= 12){				//如果大于12空格 则中间加gap
        			gap = ' '+Symbols[opts.mode]+Symbols[opts.mode]+' ';
        			startSpace = endSpace = createSpaceStr((extra-4)/2);
        			endSpace = createSpaceStr(((extra-4)/2)%2 == 0 ? (extra-4)/2: (extra-4)/2-1);
        		}else{ 
        			gap = createSpaceStr((extra-8)/2);
        		}
        	}else{
        		gap = '';
    			endSpace = createSpaceStr(extra%2 == 0 ? (extra/2) : Math.ceil(extra/2));
        	}
        	messageStr = startSpace+param.title+gap+param.content+endSpace;
        }else{
        	topSymbol = bottomSymbol =createSpaceStr(trueLen+opts.betweenLen,Symbols[opts.mode]);
        	messageStr = opts.title ? (param.title+param.content):param.content;
        }
        

        let showTemplate = [
        	topSymbol+'\n'+'*********'+messageStr+'********\n'+bottomSymbol,
        	topSymbol+'\n'+'========='+messageStr+'========\n'+bottomSymbol,
        	topSymbol+'\n'+'---------'+messageStr+'--------\n'+bottomSymbol,
        	topSymbol+'\n'+'>>>>>>>>>'+messageStr+'<<<<<<<<\n'+bottomSymbol      	     	
        ]
        console.log(showTemplate[Number(opts.mode)-1])
	}
}
myTools.print();

module.exports = myTools;

/*
 * ------------------------------
 * 
 *  @author : Rucky
 *  @cntQQ  ：344879627
 *  @info   : My local env config
 * 
 * ------------------------------
 */