import { View } from 'view-engine/view';
import { AppSettingsModel } from 'models/app-settings-model';
import { Resizable } from 'view-engine/resizable';
import { Scrollable } from 'view-engine/scrollable';
import { MenuItemView } from 'views/menu/menu-item-view';
import template from 'templates/menu/menu-section.hbs';

class MenuSectionView extends View {
    template = template;

    events = {};

    itemViews = null;

    minHeight = 55;
    autoHeigh = 'auto';

    constructor(model, options) {
        super(model, options);
        this.itemViews = [];
        this.listenTo(this.model, 'change-items', this.itemsChanged);
        this.listenTo(this, 'view-resize', this.viewResized);
        this.once('remove', () => {
            if (this.scroll) {
                this.scroll.dispose();
            }
            this.removeInnerViews();
        });
    }

    render() {
        if (!this.itemsEl) {
            super.render(this.model.attributes);
            this.itemsEl = this.model.get('scrollable') ? this.$el.find('.scroller') : this.$el;
            if (this.model.get('scrollable')) {
                this.initScroll();
                this.createScroll({
                    root: this.$el[0],
                    scroller: this.$el.find('.scroller')[0],
                    bar: this.$el.find('.scroller__bar')[0]
                });
            }
        } else {
            this.removeInnerViews();
        }
        this.model.get('items').forEach(item => {
            const itemView = new MenuItemView(item, { parent: this.itemsEl[0] });
            itemView.render();
            this.itemViews.push(itemView);
        });
        if (this.model.get('drag')) {
            const height = AppSettingsModel.instance.get('tagsViewHeight');
            if (typeof height === 'number') {
                this.$el.height();
                this.$el.css('flex', '0 0 ' + height + 'px');
            }
        }
        this.pageResized();
    }

    maxHeight() {
        return this.$el.parent().height() - 116;
    }

    removeInnerViews() {
        this.itemViews.forEach(itemView => itemView.remove());
        this.itemViews = [];
    }

    itemsChanged() {
        this.render();
    }

    viewResized(size) {
        this.$el.css('flex', '0 0 ' + (size ? size + 'px' : 'auto'));
        this.saveViewHeight(size);
    }

    saveViewHeight = _.throttle(size => {
        AppSettingsModel.instance.set('tagsViewHeight', size);
    }, 1000);
}

Object.assign(MenuSectionView.prototype, Resizable);
Object.assign(MenuSectionView.prototype, Scrollable);

export { MenuSectionView };
