import * as Net from 'net'
import localProxyServer from './localProxyServer'
import ImapCluster from './imapCluster'
import * as Compress from './compress'
import * as fs from 'fs'
import * as http from 'http'
import * as os from 'os'
import * as HostList from './hostList'

import * as json from './client.json'

const localProxyPort = '8888'

const matchLocalIp = /(^127\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)/ //|(^192\.168\.)/
const getLocalHostIp = ( ) => {
	let localIp = ''
	console.log ('=======================> getLocalHostIp start')
	Object.keys( ifaces ).forEach( ifname => {
		let alias = 0;

		ifaces[ ifname ].forEach( iface => {
			if ('IPv4' !== iface.family || iface.internal !== false) {
			// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
				return
			}
			console.log (iface)
			if ( alias >= 1 ) {
				// this single interface has multiple ipv4 addresses
				console.log ( ifname + ':' + alias, iface.address );
			} else {
				// this interface has only one ipv4 adress
				if ( !matchLocalIp.test ( iface.address ))
					localIp = iface.address
			}
			++ alias;
		})
	})

	return localIp
}
const EmailClient = false
const returnPac = 'function FindProxyForURL(url, host) { return "SOCKS 139.196.103.40:8888" }'
const filename = 'proxy/client.json.js'
const ifaces = os.networkInterfaces();
const maxIpError = 30
const dropIpMaxCount = 100
const cacheKeepTime = 1000 * 60 * 60 * 240
const localIp = getLocalHostIp ()
const rootPassword = 'jjST11XnDiUl6ew83bY7N6Ba,1n6rOERfg.GzNGtRbwTr6IC5WQH3'

const newEmail = ( data: Compress.packetBuffer ) => {
	//console.log ('newEmail come', data.uuid, data.command, data.buffer.length)
	const localProxy = socketPool.get ( data.uuid )

	if ( !localProxy ) {
		return //console.log ( `have no localProxy [${data.uuid}]`)
	}
	return localProxy.getData ( data )
}

const socketPool: Map <string, localProxyServer > = new Map ()
const blackIpList: Map < string, number > = new Map ()
const whiteIpList = []
const hostListPool: Map < string, HostList.hostListData > = new Map ()
const domainBlackListPool: string[] = ['tech.163.com']
const hostList = new HostList.hostList ( hostListPool, domainBlackListPool )
const iptableDropIp = ( ip: string ) => {
	const ip4 = ip.split (':')[3]
	if ( ip4 && ip4.length ) {
		
	}
}

	const imapCluster = new ImapCluster ( json.user, json.rootPassword, false, newEmail, false, () => {
		console.log ('imapCluster exit imap connect end!!!')
	})

	fs.access ( json.cachePath, err => {
		if ( !err ) {
			return
		}
		fs.mkdir ( json.cachePath, err => {
			if ( err )
				return console.log ( '============> mkdir cachePath error!' )
		})
	})

	const net = Net.createServer ( socket => {
		const ip = socket.remoteAddress

			let client = new localProxyServer ( json.rootPassword, socket, imapCluster, whiteIpList, cacheKeepTime, localIp, socketPool, blackIpList, hostList, () => {
				return client = null
			})

	})
	
	console.log ( 'client side start success!' )
	
	net.listen ( localProxyPort )
	



