import React from 'react';
import Fluky from 'fluky';

var matchUP = require('../../images/matchUP-white.png');

var Verifying = React.createClass({
	render() {
		return (
			<div className="preloader-wrapper middle active icon">
				<div className="spinner-layer spinner-blue">
					<div className="circle-clipper left">
						<div className="circle"></div>
					</div>
					<div className="gap-patch">
						<div className="circle"></div>
					</div>
					<div className="circle-clipper right">
						<div className="circle"></div>
					</div>
				</div>
				<div className="spinner-layer spinner-red">
					<div className="circle-clipper left">
						<div className="circle"></div>
					</div>
					<div className="gap-patch">
						<div className="circle"></div>
					</div>
					<div className="circle-clipper right">
						<div className="circle"></div>
					</div>
				</div>
				<div className="spinner-layer spinner-yellow">
					<div className="circle-clipper left">
						<div className="circle"></div>
					</div>
					<div className="gap-patch">
						<div className="circle"></div>
					</div>
					<div className="circle-clipper right">
						<div className="circle"></div>
					</div>
				</div>
				<div className="spinner-layer spinner-green">
					<div className="circle-clipper left">
						<div className="circle"></div>
					</div>
					<div className="gap-patch">
						<div className="circle"></div>
					</div>
					<div className="circle-clipper right">
						<div className="circle"></div>
					</div>
				</div>
			</div>
		)
	}
});
var Compiled = React.createClass({
	render() {
		return (
			<i className="material-icons icon icon-done">check_circle</i>
		)
	}
});
var Failed = React.createClass({
	render() {
		return (
			<i className="material-icons icon icon-error">cancel</i>
		)
	}
});

class Alert extends React.Component {
	static PropTypes = {
		status: React.PropTypes.string,
		flash: React.PropTypes.func
	};

    close = () => {
		// Set status back to ready
		if (this.props.status != 'flashing') {
			Fluky.dispatch('action.Builder.setStatus', 'ready');
		}
    }

	flush = () => {
		this.props.flush();
	}

    render() {
    	var msgBox = null;
    	var status;
		var statusText;
		var closeBtn;
		
		if (this.props.status != 'ready' && this.props.status != 'initializing') {
			closeBtn = <span className="pull-right"><i className="material-icons icon-close" onClick={ this.close }>cancel</i></span>;

			if (this.props.status === 'flashing') {
				statusText = '烧录中...';
				status = <Verifying />;
				closeBtn = null;
			} else if (this.props.status === 'flash-succeed') {
				statusText = '烧录成功！';
				status = <Compiled />;
			} else if (this.props.status === 'flash-failed-cannot-connect-device') {
				statusText = '烧录失败！无法连接装置，请检查是否已正确连接。';
				status = <Failed />;
			} else if (this.props.status === 'flash-failed' && this.props.status === 'verification-failed') {
				statusText = '烧录失败！未知的原因。';
				status = <Failed />;
			}

			msgBox = <div>
				<div className={'col s2 alert'}>
					{ closeBtn }
					<div className="card-panel grey lighten-5 z-depth-3 animated rubberBand">
						<div className="row valign-wrapper">
							<div className="col s3">
								{ status }
							</div>
							<div className="col s9">
								<span className="black-text text">
									{ statusText }
								</span>
							</div>
						</div>
					</div>
				</div>
	        	<div className="overlay" onClick={ this.close }></div>
        	</div>;
		}

        return (
        	<div>
	        	{ msgBox }
			</div>
        );
    }
}

class Toolbar extends React.Component {

	constructor(props) {
		super(props);

		var builderStore = Fluky.getState('Builder');
		this.state = {
			workspace: Fluky.getState('Blockly').workspace,
			boards_list: builderStore.boards_list,
			ports_list: builderStore.ports_list,
			selectedBoard: builderStore.selectedBoard,
			selectedPort: builderStore.selectedPort,
			generatedCode: false,
			verified: false,
			flashed: false,
			builderStatus: builderStore.status
		};
	}

	componentWillMount() {
		var self = this;

		Fluky.on('store.Builder', Fluky.bindListener(this.onChange));
		Fluky.on('store.Blockly', Fluky.bindListener(this.onChange));

		Fluky.dispatch('action.Builder.initialize');
	}

	componentWillUnmount() {
		Fluky.off('store.Blockly', this.onChange);
		Fluky.off('store.Builder', this.onChange);
	}

	tabs = () => {
		var currentTab;

		if (Fluky.getState('Tabs').name === 'components') {
			currentTab = 'codes';
		}
		if (Fluky.getState('Tabs').name === 'codes') {
			currentTab = 'components';
		}

		Fluky.dispatch('action.Tabs.setTabs', currentTab);
 	}

 	play = () => {
		Fluky.dispatch('action.WorkBoard.generateTestCode');
	}

	flash = () => {
		if (!this.state.workspace)
			return;

		Fluky.dispatch('action.Builder.flash', this.state.workspace, this.state.selectedBoard, this.state.selectedPort);
//		Fluky.dispatch('action.Builder.checkHW', this.state.selectedBoard, this.state.selectedPort);
	}

	onChange = () => {
		var builder = Fluky.getState('Builder');
		var workspace = Fluky.getState('Blockly').workspace;
		var state = {
			workspace: workspace,
			boards_list: builder.boards_list,
			ports_list: builder.ports_list,
			verified: builder.verified,
			selectedBoard: builder.selectedBoard,
			selectedPort: builder.selectedPort,
			builderStatus: builder.status
		};

		// If code was generated
		var code = builder.code;
		if (code != '') {
			state.generatedCode = true;
		}

		this.setState(state);
	}

	selectBoard = (event) => {
		this.setState({ selectedBoard: event.target.value });
	}

	selectPort = (event) => {
		Fluky.dispatch('action.Builder.selectPort', event.target.value);
	}

	render() {
		var boardList = [];
		if (!this.state.boards_list.length) {
			boardList.push(<option value='0' key={0}>Loading ...</option>);
		}

		for (var index in this.state.boards_list) {
			var board = this.state.boards_list[index];

			// We need Ardiono Uno only
			if (board.name == 'Arduino Uno') {
				boardList.push(<option value={board.id} key={index}>{board.name}</option>);
				boardList.push(<option value={board.id} key={index + 1}>Genuino</option>);
				break;
			}
		}

		var portsList = [];
		if (!this.state.ports_list.length) {
			portsList.push(<option value='0' key={0}>Scanning ports...</option>);
		}

		var compileBtn = null;
		if (this.state.boards_list.length && this.state.ports_list.length) {
			if (Fluky.getState('Tabs').name === 'components') {
				compileBtn = <button className="waves-effect waves-light btn compile-btn orange accent-3" type='button' onClick={this.play}>硬件檢測</button>;
			}
			if (Fluky.getState('Tabs').name === 'codes') {
				compileBtn = <button className="waves-effect waves-light btn compile-btn orange accent-3" type='button' onClick={this.flash}>代码烧录</button>;
			}
		}

		this.state.ports_list.forEach(function(port, index) {
			portsList.push(<option value={port} key={index}>{port}</option>);
		});

		var boardStyle = {
			display: 'none'
		};
		
		var selectLabel = {
			marginTop: '12px',
			color: '#FAFAFA'
		};

		return (
			<div id="toolBar" className={'row tool-bar z-depth-1 nav-is-visible'}>
				<div className="container">
					<select id='cb_cf_boards' style={boardStyle}></select>
					<select id='cb_cf_ports' style={boardStyle}></select>
					<select id='cb_cf_baud_rates' style={boardStyle}></select>
					<p id='cb_cf_operation_output' style={boardStyle}></p>
					<form>
						<div className={'col s1'}>
							<a href="/" className="brand-logo"><img className="tool-bar-logo" src={ matchUP } /></a>
						</div>
						<div className={'col s3'}>
							<div className={'row'}>
								<p className={'col s4 text-right'} style={selectLabel}>设备型号 :</p>
								<div className={'col s8'}>
									<select className={'browser-default'} onChange={this.selectBoard} value={this.state.selectedBoard}>
										{boardList}
									</select>
								</div>
							</div>
						</div>
						<div className={'col s3'}>
							<div className={'row'}>
								<p className={'col s4 text-right'} style={selectLabel}>传输口 :</p>
								<div className={'col s8'}>
									<select className={'browser-default'} onChange={this.selectPort} value={this.state.selectedPort}>
										{portsList}
									</select>
								</div>
							</div>
						</div>
						<div className={'col s5'}>
							<div className={'row'}>
								<div className={'col s4'}>
									{ compileBtn }
									&nbsp;
								</div>
								<div className={'col s8'}>
									<p className="switch pull-right">
										<label>
											模块拖拉
											<input id="tabs" type="checkbox" onClick={this.tabs} />
											<span className="lever"></span>
											逻辑拼接
										</label>
								    </p>
								</div>
							</div>
						</div>
					</form>
					<Alert status={this.state.builderStatus} flush={this.flash} />
				</div>
		    </div>
		);
	};
}

module.exports = Toolbar;
