import React, { Component } from 'react';
import './UpdateDrawer.css'
import { withStyles } from 'material-ui/styles';

import { CircularProgress } from 'material-ui/Progress';

import Dialog, {
	DialogActions,
	DialogContent,
	DialogTitle,
} from 'material-ui/Dialog';

import Button from 'material-ui/Button';

import axios from 'axios';
import MUIDialogStyleUtil from './MUIDialogStyleUtil'
const styles = MUIDialogStyleUtil.getTwoButtonStyle()

class UpdateDrawer extends Component {

	constructor(props) {
		super(props)

		this.state = {
			loading: false
		}
	}
	onCasesModified(updateTogether) {
		const { game, myshixun, showSnackbar, updateDialogClose } = this.props;

		// const url = `/api/v1/games/${game.identifier}/sync_modify_time`
		const url = `/tasks/${game.identifier}/sync_modify_time`
		axios.get(url, {
			// withCredentials: true,
		})
			.then((response) => {

				if (!updateTogether) {
					showSnackbar('更新状态已同步。')
				}
				updateDialogClose();
			})
			.catch((error) => {
				console.log(error);
			});

	}
	// 稍后再说
	onNextUpdate(tpmCasesModified) {
		const { tpm_cases_modified, tpm_modified, tpm_script_modified, challenge, updateDialogClose } = this.props;
		let needUpdateScript = (tpm_modified || tpm_script_modified) && challenge.st === 0;

		const { game, myshixun, showSnackbar } = this.props;
		// const url = `/myshixuns/${myshixun.identifier}/stages/${game.identifier}/system_update`

		// const url = `/api/v1/games/${game.identifier}/system_update?myshixun_id=${myshixun.id}`
		const url = `/tasks/${game.identifier}/system_update.json?myshixun_id=${myshixun.id}`
		this.setState({ loading: true })
		axios.get(url, {
			// withCredentials: true,
		})
			.then((response) => {
				this.setState({ loading: false })


				if (tpmCasesModified) {
					this.onCasesModified(true)
				}
				updateDialogClose(true);
			})
			.catch((error) => {
				console.log(error);
			});
	}

	// tpmCasesModified 如果为true，则需要调用后台接口置状态，下次就不用提醒了
	// 立即更新
	onUpdateNow(tpmCasesModified) {
		const { tpm_cases_modified, tpm_modified, tpm_script_modified, challenge, updateDialogClose } = this.props;
		let needUpdateScript = (tpm_modified || tpm_script_modified) && challenge.st === 0;

		const { game, myshixun, showSnackbar, updateChallengePath, fetchRepositoryCode } = this.props;
		if (needUpdateScript) {
			this.setState({ loading: true })

			const url = `/tasks/${game.identifier}/sync_codes.json`
			axios.get(url, {
				// withCredentials: true,
			})
				.then((response) => {
					this.setState({ loading: false })

					const { path, status } = response.data;
					if (status === -1) {
						showSnackbar(response.data.message || '更新失败，服务端错误')
					} else if (response.data) {
						if (path) {
							updateChallengePath(path);
							fetchRepositoryCode()
						}
						updateDialogClose(false, true);
						showSnackbar('更新成功，正在为您重新加载代码...')

					}

					if (tpmCasesModified) {
						this.onCasesModified(true)
					}
				})
				.catch((error) => {
					this.setState({ loading: false })

					// showSnackbar('更新失败，请求异常')
					console.log(error);
				});
		}
	}

	handleDialogClose() {
		// 必须得选择一个？
		const { updateDialogClose } = this.props;
		updateDialogClose();
	}
	// fetchRepositoryCode
	render() {
		const { myshixun, showUpdateDialog, classes } = this.props;
		const { loading } = this.state;
		const { tpm_cases_modified, tpm_modified, tpm_script_modified, challenge } = this.props;
		let needUpdateScript = (tpm_modified || tpm_script_modified) && challenge.st === 0;

		return (

			<Dialog
				disableBackdropClick={true}
				className="updateDialog"
				open={showUpdateDialog && (tpm_cases_modified || needUpdateScript)}
				onClose={() => this.handleDialogClose()}
			>
				<DialogTitle id="alert-dialog-title">{"更新通知"}</DialogTitle>
				<DialogContent id="dialog-content">
					<div style={{ textAlign: 'center' }}>
						{tpm_cases_modified && needUpdateScript ?
							<div>
								关卡任务的代码文件和测试集有更新啦~<br></br>更新操作将保留已完成的评测记录和成绩。<br></br>还未完成评测的任务代码，请自行保存！
		            		</div>
							:
							tpm_cases_modified ?
								<div>
									本关{challenge.st === 0 ? '测试集' : '答案'}已更新，您可以重新评测。<br></br>本次更新不影响已获得的经验值。
		            		</div> :
								<div>
									关卡任务的代码文件有更新啦~<br></br>更新操作将保留已完成的评测记录和成绩。<br></br>还未完成评测的任务代码，请自行保存！
		            		</div>
						}
					</div>
				</DialogContent>
				<DialogActions id="dialog-actions" >
					{needUpdateScript ?
						<React.Fragment>
							<Button
								disabled={loading}
								className={"nextUpdate " + classes.button + ' ' + classes.buttonGray} onClick={() => this.onNextUpdate(tpm_cases_modified)} color="primary" >
								稍后再说
			            </Button>
							<Button
								disabled={loading}
								variant="raised" onClick={() => this.onUpdateNow(tpm_cases_modified)} color="primary" className={"updateNow " + classes.button}>
								立即更新
			            </Button>
							{loading && <CircularProgress size={24} className={classes.buttonProgress} />}
						</React.Fragment> :
						<Button onClick={() => this.onCasesModified()} color="primary" className={"nextUpdate " + classes.button}>
							知道啦
		            </Button>
					}
				</DialogActions>
			</Dialog>
		);
	}
}


export default withStyles(styles)(UpdateDrawer);
