import React from 'react';
import _ from 'lodash';
import Reflux from 'reflux';
import RefluxImmutableStoreMixin from 'reflux-immutable/StoreMixin';
import QandaStore from 'trc-client-core/src/qanda/QandaStore';   

import Tag from '../components/Tag';
import UserStore from '../user/UserStore';

var QandaSidebar = React.createClass({
    displayName: 'QandaSidebar',
    mixins: [
        Reflux.listenTo(QandaStore, 'onStoreChange'),
        RefluxImmutableStoreMixin
    ],
    getStoreState() {
        return {
            tags: QandaStore.get('tags')
        };
    },
    render: function() {
        var fadeinclass = (this.state.tags.size) ? 'is-in' : 'is-out';
        return (
            <div>                
                {this.renderEditTableButton()}
                <h2 className="hug-top">Popular Tags</h2>
                <ul className={`List List-inline row hug-top transition-fadein ${fadeinclass}`}>
                    {this.renderTags()}
                </ul>
            </div>
        );
    },
    renderTags: function () {
        var tags = this.state.tags.toJS();
        var max = _.max(tags, 'count').count;
        var min = _.min(tags, 'count').count;

        return _(tags)
        
            // Remove Unused Tags
            .filter(function(i){ 
                return i.count > 0;
            })

            // Apply classes based on their distrubution
            .map(function(value){
                var index = (value.count - min) / (max - min);
                value.size = 'delta';

                if (index > 0.67) {
                    value.size = 'beta';
                } else if (index <= 0.67 && index > 0.33) {
                    value.size = 'gamma';
                }

                return value;
            })

            // render html
            .map((value, key) => {
                return <li key={key}><Tag name={value.name} size={value.size} /></li>;
            })
            .value();
    },
    renderEditTableButton: function () {
        if (UserStore.is('ROLE_SUPER_ADMIN')) {
            return (
                <ul className="IconList IconList-edit">
                    <li><a data-icon={String.fromCharCode(9999)} href="/#/product/qanda/edit">{"Q & A Admin Area"}</a></li>
                </ul>
            );
        }
    }
});

export default QandaSidebar;