/**
 * Copyright (c) 2016-present, DesDev, Inc.
 * All rights reserved.
 *
 * Official:http://dedeampz.dedecms.com
 *
 * Company:http://www.desdev.cn
 */
const {
	dialog
} = require('electron').remote
const request = require('request');
const progress = require('request-progress');
const decompress = require('decompress');

var PHPIsInstall = fs.existsSync(PHPCli);
var ApacheIsInstall = fs.existsSync(ApacheCli);
var MariadbIsInstall = fs.existsSync(MariadbCli);

var PHPINI = path.join(ConfigDir, 'php.ini');
var ApacheINI = path.join(ConfigDir, 'httpd.conf');
var ApacheTempINI = path.join(TempDir, 'httpd.conf');
var ApacheVhostsINI = path.join(ConfigDir, 'httpd-vhosts.conf');
var MariadbINI = path.join(ConfigDir, 'my.ini');
var MariadbTempINI = path.join(TempDir, 'my.ini');
var PHPTempINI = path.join(TempDir, 'php.ini');

var PHPINITemplate = path.join(SrcDir, 'php.ini');
var ApacheINITemplate = path.join(SrcDir, 'httpd.conf');
var ApacheVhostsINITemplate = path.join(SrcDir, 'httpd-vhosts.conf');
var MariadbINITemplate = path.join(SrcDir, 'my.ini');

const execSync = require('child_process').execSync;

var initAMP = {
	initConfig : function(cb){
		if (!fs.existsSync(ApacheINI))
		{
			var ApacheINITPLStr = fs.readFileSync(ApacheINITemplate).toString();
			var ApacheINIStr = this.__parseConfig(ApacheINITPLStr);
			fs.writeFileSync(ApacheINI, ApacheINIStr);
			Websites.createOne("default","默认站点","localhost",path.join(WebsitesDir, 'default'));
		}
		
		if (!fs.existsSync(MariadbINI))
		{
			var MariadbINITPLStr = fs.readFileSync(MariadbINITemplate).toString();
			var MariadbINIStr = this.__parseConfig(MariadbINITPLStr);
			fs.writeFileSync(MariadbINI, MariadbINIStr);
		}
		
		if (!fs.existsSync(PHPINI))
		{
			var PHPINITPLStr = fs.readFileSync(PHPINITemplate).toString();
			var PHPINIStr = this.__parseConfig(PHPINITPLStr);
			fs.writeFileSync(PHPINI, PHPINIStr);
		}
		cb(true);
	},
	checkApacheInstall: function() {
		if (!ApacheIsInstall) {
			return false;
		}
		if (DedeAMPZ.getApacheVersion() == 'unknow') {
			return false;
		}
		return true;
	},
	
	installApache: function(cb) {
		if (ApacheIsInstall) {
			$("#ControlApache").show();
			$("#InstallApacheProcess").hide();
			console.log('Apache已经安装！');
			log.debug('call initAMP.installApache,Apache is installed');
			cb(false);
			return true;
		};
		$("#ControlApache").hide();
		$("#InstallApacheProcess").show();
		if (!fs.existsSync(ApacheINITemplate) || !fs.existsSync(ApacheVhostsINITemplate)) {
			console.log('Apache配置模板文件丢失,请检查安装包是否完整!');
			log.debug('call initAMP.installApache,Apache ini is losted');
			cb(false);
			return false;
		}
		var ApacheINITPLStr = fs.readFileSync(ApacheINITemplate).toString();
		var ApacheINIStr = this.__parseConfig(ApacheINITPLStr);

		//var ApacheVhostsINITPLStr = fs.readFileSync(ApacheVhostsINITemplate).toString();
		//var ApacheVhostsINIStr = this.__parseConfig(ApacheVhostsINITPLStr);

		console.log('开始下载Apache……');
		log.info('call initAMP.installApache,start download Apache');
		try {
			progress(request('http://dedeampz.dedecms.com/release/Apache.zip'), {})
				.on('progress', function(state) {
					$("#InstallApacheProcessBar").width(Math.ceil(state.percentage * 100 * 0.8) + "%");
					$("#InstallApacheProcessTitle").html('已下载' + Math.ceil(state.percentage * 100 * 0.8) + "%");
					//console.log('progress', state);
				})
				.on('error', function(err) {
					log.error('call initAMP.installApache,download Apache is error', err);
					cb(false);
				})
				.on('end', function() {
					$("#InstallApacheProcessBar").width("90%");
					$("#InstallApacheProcessTitle").html('正在解压Apache');
					console.log('Apache下载成功，开始解压缩');
					log.info('call initAMP.installApache,download Apache is successfull');
					decompress(path.join(TempDir, 'Apache.zip'), ApacheDir).then(files => {
						fs.writeFileSync(ApacheINI, ApacheINIStr);
						fs.unlinkSync(path.join(TempDir, 'Apache.zip'));
						Websites.createOne("default","默认站点","localhost",path.join(WebsitesDir, 'default'));
						$("#InstallApacheProcessBar").width("100%");
						$("#InstallApacheProcessTitle").html('成功安装Apache');
						$("#ShowApacheVersion").html("version:" + DedeAMPZ.getApacheVersion());
						$("#ControlApache").show();
						$("#InstallApacheProcess").hide();
						cb(true);
						console.log('Apache安装成功');
						log.info('call initAMP.installApache,install Apache is successfull');
					});
				})
				.pipe(fs.createWriteStream(path.join(TempDir, 'Apache.zip')));

		} catch (e) {
			console.log(e);
		}

	},
	checkPHPInstall: function() {
		if (!PHPIsInstall) {
			return false;
		}
		if (DedeAMPZ.getPHPVersion() == 'unknow') {
			return false;
		}
		return true;
	},
	installPHP: function() {
		if (PHPIsInstall) {
			$("#ControlPHP").show();
			$("#InstallPHPProcess").hide();
			console.log('PHP已经安装');
			log.debug('call initAMP.installPHP,PHP is installed');
			return true;
		}
		$("#ControlPHP").hide();
		$("#InstallPHPProcess").show();
		if (!fs.existsSync(PHPINITemplate)) {
			console.log('PHP配置模板文件丢失,请检查安装包是否完整');
			log.debug('call initAMP.installPHP,PHP ini is losted');
			return false;
		}
		var PHPINITPLStr = fs.readFileSync(PHPINITemplate).toString();
		var PHPINIStr = this.__parseConfig(PHPINITPLStr);
		console.log('开始下载PHP……');
		log.info('call initAMP.installPHP,start download PHP');
		try {
			progress(request('http://dedeampz.dedecms.com/release/PHP.zip'), {})
				.on('progress', function(state) {
					$("#InstallPHPProcessBar").width(Math.ceil(state.percentage * 100 * 0.8) + "%");
					$("#InstallPHPProcessTitle").html('已下载' + Math.ceil(state.percentage * 100 * 0.8) + "%");
					//console.log('progress', state);
				})
				.on('error', function(err) {
					log.error('call initAMP.installPHP,download PHP is error', err);
				})
				.on('end', function() {
					$("#InstallPHPProcessBar").width("90%");
					$("#InstallPHPProcessTitle").html('正在解压PHP');
					log.info('call initAMP.installPHP,download PHP is successfull');
					decompress(path.join(TempDir, 'PHP.zip'), PHPDir).then(files => {
						fs.writeFileSync(PHPINI, PHPINIStr);
						fs.unlinkSync(path.join(TempDir, 'PHP.zip'));
						console.log('PHP安装成功');
						$("#InstallPHPProcessBar").width("100%");
						$("#InstallPHPProcessTitle").html('成功安装PHP');
						$("#ShowPHPVersion").html("version:" + DedeAMPZ.getPHPVersion());
						$("#ControlPHP").show();
						$("#InstallPHPProcess").hide();
						log.info('call initAMP.installPHP,install PHP is successfull');
					});
				})
				.pipe(fs.createWriteStream(path.join(TempDir, 'PHP.zip')));

		} catch (e) {
			console.log(e);
		}
	},
	checkMariadbInstall: function() {
		if (!MariadbIsInstall) {
			return false;
		}
		if (DedeAMPZ.getMariadbVersion() == 'unknow') {
			return false;
		}
		return true;
	},
	installMariadb: function() {
		if (MariadbIsInstall) {
			$("#ControlMariadb").show();
			$("#InstallMariadbProcess").hide();
			console.log('Mariadb已经安装！');
			log.debug('call initAMP.installMariadb,Mariadb is installed');
			return false;
		};
		$("#ControlMariadb").hide();
		$("#InstallMariadbProcess").show();
		if (!fs.existsSync(MariadbINITemplate)) {
			console.log('Mariadb配置模板文件丢失,请检查安装包是否完整!');
			log.debug('call initAMP.installMariadb,Mariadb ini is losted');
			return false;
		}
		var MariadbINITPLStr = fs.readFileSync(MariadbINITemplate).toString();
		var MariadbINIStr = this.__parseConfig(MariadbINITPLStr);
		//console.log(MariadbINIStr);
		console.log('开始下载Mariadb……');
		log.info('call initAMP.installMariadb,start download Mariadb');

		try {
			progress(request('http://dedeampz.dedecms.com/release/Mariadb.zip'), {})
				.on('progress', function(state) {
					$("#InstallMariadbProcessBar").width(Math.ceil(state.percentage * 100 * 0.8) + "%");
					$("#InstallMariadbProcessTitle").html('已下载' + Math.ceil(state.percentage * 100 * 0.8) + "%");
					//console.log('progress', state);
				})
				.on('error', function(err) {
					log.error('call initAMP.installMariadb,download Mariadb is error', err);
				})
				.on('end', function() {
					console.log('Mariadb下载成功，开始解压缩');
					$("#InstallMariadbProcessBar").width("90%");
					$("#InstallMariadbProcessTitle").html('正在解压Mariadb');
					log.info('call initAMP.installMariadb,download Mariadb is successfull');
					decompress(path.join(TempDir, 'Mariadb.zip'), MariadbDir).then(files => {
						fs.writeFileSync(MariadbINI, MariadbINIStr);
						fs.unlinkSync(path.join(TempDir, 'Mariadb.zip'));
						$("#InstallMariadbProcessBar").width("100%");
						$("#InstallMariadbProcessTitle").html('成功安装Mariadb');
						$("#ShowMariadbVersion").html("version:" + DedeAMPZ.getPHPVersion());
						$("#ControlMariadb").show();
						$("#InstallMariadbProcess").hide();
						console.log('Mariadb安装成功');
						log.info('call initAMP.installMariadb,install Mariadb is successfull');
					});
				})
				.pipe(fs.createWriteStream(path.join(TempDir, 'Mariadb.zip')));

		} catch (e) {
			console.log(e);
		}
	},
	__parseConfig: function(str) {
		return Util.parseConfig(str);
	}
};