/**
 * H5 开发服务器配置
 * - proxy：解决浏览器跨域
 * - host 0.0.0.0 + public：局域网同事访问时 sockjs 不连 localhost
 *
 * 小程序：编译后去掉 uni-app 注入的 shadow-grey.png CDN 预加载（常 timeout）
 */
const fs = require('fs')
const path = require('path')
const os = require('os')

function getLanIp() {
	const nets = os.networkInterfaces()
	for (const name of Object.keys(nets)) {
		for (const net of nets[name]) {
			if (net.family === 'IPv4' && !net.internal) {
				return net.address
			}
		}
	}
	return '127.0.0.1'
}

const DEV_PORT = 8080
const LAN_IP = getLanIp()

/** 匹配 uni-app 注入的 dcloud CDN 阴影图 background */
const DCLOUD_SHADOW_CSS_RE = /\s*background(-image)?:\s*url\(\S*?\/\/[\w.-]*?dcloud\.net\.cn\S*?\)\s*;?/gi

function stripDcloudShadowCss(dir) {
	if (!dir || !fs.existsSync(dir)) return
	const stack = [dir]
	while (stack.length) {
		const cur = stack.pop()
		let entries
		try {
			entries = fs.readdirSync(cur)
		} catch (e) {
			continue
		}
		entries.forEach((name) => {
			const full = path.join(cur, name)
			let stat
			try {
				stat = fs.statSync(full)
			} catch (e) {
				return
			}
			if (stat.isDirectory()) {
				stack.push(full)
				return
			}
			if (!/\.(wxss|css|scss)$/i.test(name)) return
			try {
				const raw = fs.readFileSync(full, 'utf8')
				if (!DCLOUD_SHADOW_CSS_RE.test(raw)) return
				DCLOUD_SHADOW_CSS_RE.lastIndex = 0
				fs.writeFileSync(full, raw.replace(DCLOUD_SHADOW_CSS_RE, ''), 'utf8')
			} catch (e) {}
		})
	}
}

class RemoveUniCdnShadowPlugin {
	apply(compiler) {
		compiler.hooks.done.tap('RemoveUniCdnShadowPlugin', () => {
			const outDir = process.env.UNI_OUTPUT_DIR
			if (outDir) stripDcloudShadowCss(outDir)
		})
	}
}

module.exports = {
	devServer: {
		host: '0.0.0.0',
		port: DEV_PORT,
		disableHostCheck: true,
		// 热更新 websocket 使用局域网 IP，避免同事浏览器去连他们自己的 localhost
		public: `${LAN_IP}:${DEV_PORT}`,
		proxy: {
			'/api': {
				// target: 'https://img.ifarmcloud.com/deploymentApi',
				target: 'http://192.168.1.6:8081',
				changeOrigin: true,
				secure: false
			}
		}
	},
	configureWebpack: {
		plugins: [new RemoveUniCdnShadowPlugin()]
	}
}
