import React from 'react';

import PureRenderMixin from 'react-addons-pure-render-mixin';
import { TextInput, Icon } from 'lego-on-react';
import StoreMixin from 'lib/StoreMixin';

import ResourcesStore from 'stores/Resources';
import PermissionStore from 'stores/Permissions';
import ConfigStore from 'stores/Config';

import Tabs from 'lego-ui/Tabs';
import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
import Main from 'components/Main';
import ServiceHeader from 'components/ServiceHeader';
import ServiceResource from 'components/ServiceResource';

import ServiceDetails from 'components/ServiceDetails';
import Responsible from './Responsible';

import searchIcon from '../../../static/i/search.svg';

import './index.css';

export default React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const serviceSlug = this._getServiceSlug(this.props);
        const items = ResourcesStore.getList(serviceSlug);
        const editable = PermissionStore.allowsServiceDataUpdate(serviceSlug);

        return { items, filteredItems: items.slice(), serviceSlug, editable };
    },

    _getServiceSlug(props) {
        return props.serviceSlug || props.params.serviceSlug;
    },

    componentDidUpdate(prevProps) {
        if (this._getServiceSlug(this.props) !== this._getServiceSlug(prevProps)) {
            this.setState(this.getStoreState());
        }
    },

    componentDidMount() {
        this.subscribe([ResourcesStore, PermissionStore]);
    },

    _renderList() {
        return (
            <div className="resources-list">
                {this.state.filteredItems.map(this._renderListItem)}
            </div>
        );
    },

    _renderListItem(item) {
        const { serviceSlug } = this.state;
        const { id } = item;

        let { resourceUrlTemplate, resourceLinkTarget } = this.props;

        resourceUrlTemplate = resourceUrlTemplate || Url.getPath('services/${serviceSlug}/resources/${id}');

        const resourceUrl = Url.build(resourceUrlTemplate, {
            serviceSlug,
            id,
            tld: ConfigStore.get('app.tld'),
        });

        return (
            <ServiceResource
                key={`resource-${id}`}
                id={`#${id}`}
                url={resourceUrl}
                target={resourceLinkTarget}
                name={item.metadata.name}
                description={item.metadata.description}
                serviceSlug={serviceSlug}
            />
        );
    },

    _onChangeFilter(e) {
        let query = e.toLowerCase();

        this.setState({
            filter: e,
            filteredItems: this.state.items.filter(({ id, metadata: { name, description } }) =>
                id.indexOf(query) > -1 ||
                name && name.toLowerCase().indexOf(query) > -1 ||
                description && description.toLowerCase().indexOf(query) > -1
            ),
        });
    },

    render() {
        const { filter, serviceSlug } = this.state;
        const responsibleId = ResourcesStore.getResponsibleId(serviceSlug);

        return (
            <Main cls="resources-service">
                <ServiceHeader serviceSlug={serviceSlug} />
                {responsibleId &&
                <ServiceDetails>
                    <ServiceDetails.Item
                        title={i18n(`service_page.${serviceSlug}.responsible`) ||
                            i18n('service_page.default.responsible')}
                    >
                        <Responsible serviceSlug={serviceSlug} />
                    </ServiceDetails.Item>
                </ServiceDetails>}
                <Tabs selectedTabId="resources">
                    <Tabs.Item
                        id="resources"
                        title={i18n(`service_page.${serviceSlug}.resources`) ||
                        i18n('service_page.default.resources')}
                    >
                        <div className="resources-actions">
                            <TextInput
                                theme="normal"
                                size="m"
                                type="text"
                                pin="round-round"
                                placeholder={i18n(`service_page.${serviceSlug}.filter`) ||
                                    i18n('service_page.default.filter')}
                                has-icon="true"
                                iconRight={<Icon url={searchIcon} />}
                                onChange={this._onChangeFilter}
                                text={filter}
                            />
                        </div>
                        {this._renderList()}
                    </Tabs.Item>
                </Tabs>
            </Main>
        );
    },

});
