import React from 'react';
import classNames from 'classnames';

import SocketService from 'services/SocketService';
import ValueFormat from 'utils/ValueFormat';
import SocketSubscriptionMixin from 'mixins/SocketSubscriptionMixin';
import PureRenderMixin from 'react-addons-pure-render-mixin';

import TransferConstants from 'constants/TransferConstants';
import IconConstants from 'constants/IconConstants';
import SettingConstants from 'constants/SettingConstants';

import Dropdown from 'components/semantic/Dropdown';
import { MenuItemLink } from 'components/semantic/MenuItem';


const MAX_LIMIT = 1024*1024*1024;

const setSetting = (key, value) => {
	SocketService.post(SettingConstants.SETTINGS_SET_URL, {
		[key]: value,
	});
//		.then()
//		.catch();
};

const getLimiterItems = (x, lineSpeed, settingKey) => {
	lineSpeed = lineSpeed * 1024 / 8;

	const disabled = x > 0 ? false : true;
	if (!x) {
		x = lineSpeed;
	}

	const values = [ 0 /* disabled */, x /* current value */,
		x + 2, x + 5, x + 10, x + 50,
		x - 2, x - 5, x - 10, x - 50,
		x * 6 / 5, x * 2, x * 4,
		x * 5 / 6, x / 2, x / 4,
	];

	const minDelta = (x >= 1024) ? (20 * Math.pow(1024, Math.floor(Math.log(x) / Math.log(1024.)) - 1)) : 
		(x >= 100) ? 5 : 0; // aint 5KB/s accurate enough?
	
	values.filter(i => {
		return i < 0 || 
			i > MAX_LIMIT || 
			(x === lineSpeed && (i > (lineSpeed*1.2))) || // dont show over 1.2 * connectionspeed as default
			(minDelta && i != x && Math.abs(i - x) < minDelta); // not too close to the original value
	});

	const menuItems = values
		.sort((a, b) => a - b)
		.map(value => {
			const active = (disabled && !value) || (!disabled && value === x);

			return (
				<MenuItemLink 
					key={ value }
					onClick={ () => setSetting(settingKey, value) }
					disabled={ active }
					active={ active }
				>
					{ !value ? 'Disabled' : ValueFormat.formatSpeed(value * 1024) }
				</MenuItemLink>
			);
		}, []);

	return menuItems;
};

const LimiterIcon = ({ icon, limit, lineSpeed, settingKey, color, cornerIcon }) => {
	const className = classNames(
		'scrolling right bottom pointing',
		{ 'enabled': limit }
	);

	const mainIconClass = classNames(
		'dashboard icon',
		{ [color]: limit },
		{ grey: !limit }
	);

	return (
		<div className="item">
			<Dropdown 
				triggerIcon={ 
					<i className="icons">
						<i className={ mainIconClass }/>
						<i className={ cornerIcon + ' corner icon' }/>
					</i>
				}
				className={ className }
				//contextGetter={ _ => '.' + componentId }
			>
				{ getLimiterItems(limit, lineSpeed, settingKey) }
			</Dropdown>
		</div>
	);
};

const LimiterBar = React.createClass({
	mixins: [ PureRenderMixin, SocketSubscriptionMixin() ],
	onSocketConnected(addSocketListener) {
		addSocketListener(TransferConstants.MODULE_URL, TransferConstants.STATISTICS, this.onStatsReceived);
	},

	fetchStats() {
		SocketService.get(TransferConstants.STATISTICS_URL)
			.then(this.onStatsReceived)
			.catch(error => console.error('Failed to fetch transfer statistics', error.message));
	},

	componentDidMount() {
		this.fetchStats();
	},

	onStatsReceived(data) {
		const newState = Object.assign({}, this.state, data);
		this.setState(newState);
	},

	getInitialState() {
		return {
			limit_down: 0,
			limit_up: 0,
		};
	},

	render: function () {
		return (
			<div className={ classNames('ui centered list limiter-icons', this.props.className) }>
				<LimiterIcon 
					color={ 'green' }
					cornerIcon={ IconConstants.DOWNLOAD }
					limit={ this.state.limit_down }
					lineSpeed={ 100 }
					settingKey="download_limit_main"
				/>
				<LimiterIcon 
					color={ 'red' }
					cornerIcon={ IconConstants.UPLOAD }
					limit={ this.state.limit_up }
					lineSpeed={ 100 }
					settingKey="upload_limit_main"
				/>
			</div>
		);
	}
});

export default LimiterBar;
