'use strict';

import React from 'react/addons';
import Reflux from 'reflux';
import $ from 'jquery';

import FileNode from './FileNode.jsx';

import WikiActions from './WikiActions.jsx';
import fileTreeStore from './wiki-home-store.jsx';
import dataAccess from '../service/dataAccess.jsx';

import Search from './searchBar.jsx';
import {constants} from '../constants.jsx';

import {sidebarScrollPositionStore} from './sidebar-scroll-position-store.jsx';

export default React.createClass({
    mixins: [Reflux.connect(fileTreeStore, 'store'),
        Reflux.connect(sidebarScrollPositionStore, 'scrollInfo'),
    ],

    lastTargetUrl: null,

    componentDidUpdate() {
        if (this.lastTargetUrl != this.state.scrollInfo.targetUrl) {
            var $sidebar = $(this.refs.sidebar.getDOMNode());
            var $target = $sidebar.find('[data-url="' + this.state.scrollInfo.targetUrl + '"]');

            this.lastTargetUrl = this.state.scrollInfo.targetUrl;

            var scrollTop = $sidebar.scrollTop(), position = $target.offset().top;
            $sidebar.scrollTop(scrollTop + position - constants.scrollMargin);
        }
    },

    render () {
        var fileTreeRoot = this.state.store.fileTree;
        $('.sidebar').scroll(function () {
            var $this = $(this);
            console.log($(this).scrollTop())
            if ($this.scrollTop() > 1) {
                $('.input-wrap input').hide();
                $('.input-wrap').css({'position': 'fixed', 'top': '20px'}).animate({width: "16px", 'left': '264px'}, 200);
                $('#matchRes').hide();
            }
            if ($this.scrollTop() < 1) {
                $('.input-wrap input').attr('style', '');
                $('.input-wrap').stop(true).removeAttr('style');
                $('#searchInput').focus();
            }
        })
        return (
            <div className="sidebar-wrapper">
                <div className="sidebar" ref="sidebar">
                    <div class="sliderbar-search">
                        <Search />
                    </div>

                    <div className="sidebar-content">
                        <FileNode node={fileTreeRoot} level={0}/>
                    </div>
                </div>
            </div>
        );
    }
});
