/*
 * This file is part of OsmInEdit, released under ISC license (see LICENSE.md)
 *
 * Copyright (c) Adrien Pavie 2019
 * Copyright (c) Daimler AG 2019
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

import React, { Component } from 'react';
import Body from './Body';
import Button from 'react-bootstrap/Button';
import Dropzone from 'react-dropzone';
import Modal from 'react-bootstrap/Modal';
import ButtonGroup from 'react-bootstrap/ButtonGroup';
import ContentSave from 'mdi-react/ContentSaveIcon';
// import MapCheck from 'mdi-react/MapCheckIcon';
import Import from 'mdi-react/ImportIcon';
import Export from 'mdi-react/ExportIcon';
import FloorImageryButtons from './common/FloorImageryButtons';
// import I18n from '../config/locales/ui';
import IndoorEditButtons from './common/IndoorEditButtons';
import PubSub from 'pubsub-js';
import Undo from 'mdi-react/UndoIcon';
import Redo from 'mdi-react/RedoIcon';

/**
 * Toolbar is a panel where user can access tools related to current mode of the editor.
 */
class Toolbar extends Component {
	state = {
		isImport: false,
		isImported: false
	}

	loadedData = null

	_onSave() {
		if(this.props.mode === Body.MODE_FLOOR_IMAGERY) {
			PubSub.publish("body.floorimagery.save");
		}
		else {
			PubSub.publish("body.mode.set", { mode: Body.MODE_CHANGESET })
		}
	}

	_onImport = () => {
		// console.log("click import");
		this.setState({
			isImport: true
		});
	}

	_onExport = () => {
		// console.log("click export");
		PubSub.publish("body.draw.export");
	}

	_Import = () => {
		if(this.state.isImported){
			// console.log("import");
			PubSub.publish("body.draw.loaded", this.loadedData);
			this.setState({
				isImported: false,
				isImport: false
			});
		}
	}

	_onCancleImport = () => {
		// console.log("_onCancleImport");
		this.setState({
			isImport: false
		});
	}
	
	_onDropImages(files) {
		if(files.length > 0) {
			// Full config file
			if(files.length === 1 && files[0].type === "application/json") {
				// Parse
				const reader = new FileReader();
				reader.onload = () => {
					try {
						const json = JSON.parse(reader.result);
						// console.log(json);

						if(json && "type" in json) {
							if(json.type === "FeatureCollection"){
								this.loadedData = json;
								this.setState({
									isImported: true
								});
								alert("文件上传成功！");
							}
						}
					}
					catch(e) { console.error(e); }
				};
				reader.readAsText(files[0]);
			}
		}
	}

	render() {
		let canUndo, canRedo, canSave, nbEdits;

		if(this.props.mode === Body.MODE_FLOOR_IMAGERY) {
			canUndo = window.imageryManager.canUndo();
			canRedo = window.imageryManager.canRedo();
			canSave = window.imageryManager.getFloorImages().length > 0;
			nbEdits = window.imageryManager.getAmountEdits();
		}
		else {
			canUndo = window.vectorDataManager.canUndo();
			canRedo = window.vectorDataManager.canRedo();
			canSave = canUndo;
			nbEdits = window.vectorDataManager.getAmountEdits();
		}

		return <div className="app-toolbar p-2">
			<div className="d-flex justify-content-between">
				<div>
					{this.props.mode === Body.MODE_FLOOR_IMAGERY ?
						<FloorImageryButtons {...this.props} />
						:
						<IndoorEditButtons {...this.props} />
					}
				</div>

				<div>
					<ButtonGroup className="mr-2" aria-label="Undo and redo">
						<Button
							variant="outline-secondary"
							size="sm"
							disabled={!canUndo}
							title="取消上一步操作"//{I18n.t("Cancel last operation")}
							onClick={() => PubSub.publish("body.action.undo")}
						>
							<Undo />
						</Button>

						<Button
							variant="outline-secondary"
							size="sm"
							disabled={!canRedo}
							title="应用上一步取消的操作"//{I18n.t("Apply again last cancelled operation")}
							onClick={() => PubSub.publish("body.action.redo")}
						>
							<Redo />
						</Button>
					</ButtonGroup>

					{/* <Button
						variant="primary"
						size="sm"
						className="mr-2"
						active={this.props.mode === Body.MODE_PREVIEW}
						disabled={this.props.mode === Body.MODE_PREVIEW}
						onClick={() => PubSub.publish("body.preview.open")}
						title={I18n.t("Preview your changes on indoor=")}
					>
						<MapCheck />
						<span className="hide-mdDown">{I18n.t("Preview")}</span>
					</Button> */}
					
					<Button
						variant="primary"
						size="sm"
						className="mr-2"
						onClick={this._onImport}
						title={"导入数据文件"}
					>
						{/* <MapCheck /> */}
						<Import />
						<span className="hide-mdDown">导入{/*I18n.t("Preview")*/}</span>
					</Button>
					
					<Button
						variant="primary"
						size="sm"
						className="mr-2"
						onClick={this._onExport}
						title={"导出数据文件并下载到本地"}
					>
						<Export />
						<span className="hide-mdDown">导出</span>
						{nbEdits > 0 && " ("+nbEdits+")"}
					</Button>

					<Button
						variant={nbEdits < 30 ? "success" : (nbEdits < 100 ? "warning" : "danger")}
						size="sm"
						disabled={!canSave}
						//title={this.props.mode === Body.MODE_FLOOR_IMAGERY ? I18n.t("Save positionning of floor plans") : I18n.t("Send your changes to OpenStreetMap")}
						title={this.props.mode === Body.MODE_FLOOR_IMAGERY ? "保存平面图的定位" : "保存数据"}
						onClick={() => this._onSave()}
					>
						<ContentSave />
						<span className="hide-mdDown">保存{/*I18n.t("Save")*/}</span>
						{nbEdits > 0 && " ("+nbEdits+")"}
					</Button>
				</div>
				<Modal show={this.state.isImport} onHide={this._onCancleImport} size="lg">
					<Modal.Header closeButton>
						<Modal.Title>导入文件</Modal.Title>
					</Modal.Header>
					<Modal.Body>
						<Dropzone
							accept="application/json"
							onDrop={files => this._onDropImages(files)}
						>
							{({getRootProps, getInputProps}) => (
								<div className="dropzone m-0 mt-3 w-100" {...getRootProps()}>
									<input {...getInputProps()} />
									<p>
									将您的数据文件拖放到此处（或单击打开文件浏览器）<br />
										<small>支持的格式: JSON</small>
									</p>
								</div>
							)}
						</Dropzone>
					</Modal.Body>
					<Modal.Footer>
						<Button variant="success" onClick={this._Import}>
							导入
						</Button>
					</Modal.Footer>
				</Modal>
			</div>
		</div>;
	}
}

export default Toolbar;
