import React from 'react/addons';
import $ from 'jquery';
import '../styles/wiki-page.less';
import 'highlight.js/styles/default.css';
import {constants} from './constants.jsx';

import util from './utils/util.jsx';

import PageApp from './wiki-page/PageApp.jsx';
import PreviewActions from './wiki-page/PreviewActions.jsx';
import previewStore from './wiki-page/preview-store.jsx';

var pageVars = {
    $window: $(window),
    $body: null
};

var topFrame = window.parent;
if (!topFrame.WikiActions) {
    // 在预览的区域中显示内容
    var isInPreview = true;
    // 需要上探多一层才能获得 WikiActions 的对象 - 即wiki的框架页
    topFrame = window.parent.parent;

    // 需要PreviewActions来关掉preview
    var outerPageFrame = window.parent;
} else {
    isInPreview = false
}

// 暴露本window的Actions给预览区域
window.PreviewActions = PreviewActions;

var pageMethods = {
    scrollPage() {
        var hash = location.hash.replace(/^#/, '');
        hash = hash || '{}';

        var hashParams = util.parseHashParams(hash);
        if (hashParams.tag) {
            var target = $('[tag-hash=' + hashParams.tag + ']');
        } else if (hashParams.linkTag) {
            target = $('[link-tag=' + hashParams.linkTag + '][link-seq=' + hashParams.linkSeq + ']');
        }

        if (target) {
            target.addClass('highlighted');
            setTimeout(function() {
                target.removeClass('highlighted');
            }, 2000);
            var scrollTop = target.position().top;
            pageVars.$window.scrollTop(scrollTop - constants.scrollMargin);
        }
    }
};

var initMethods = {
    initAnchorClicked() {
        $(document).on('click', 'a', function (e) {
            var $t = $(this);

            if ($t.attr('link-tag')) {
                topFrame.WikiActions.wikiLinkClicked({
                    tag: $t.attr('link-tag')
                });

                // 如果点击链接, 需要把当前的预览区关掉
                outerPageFrame && outerPageFrame.PreviewActions.deactivatePreview();
                setTimeout(x => pageMethods.scrollPage());
            } else if ($t.attr('tag-hash')) {
                if (isInPreview) {
                    topFrame.WikiActions.wikiLinkClicked({
                        tag: $t.attr('tag-hash')
                    });
                }
                e.stopPropagation();
            } else {
                $t.attr('target', '_blank');
            }
        });
    },

    initDocumentClicked() {
        $(document).on('click', function () {
            PreviewActions.clickOnPage();
        });
    },
    initAnchorHovering() {
        // 根据悬浮的对象的类型进行逻辑分发
        var dispatchLinkHovering = (anchor, callbacks) => {
            var $a = $(anchor);
            if ($a.attr('link-tag') && callbacks.link) {
                var tagHash = $a.attr('link-tag');
                callbacks.link($a, tagHash);
            } else if ($a.attr('tag-hash') && callbacks.tag) {
                var tagHash = $a.attr('tag-hash');
                callbacks.tag($a, tagHash);
            }
            if (callbacks.both) {
                callbacks.both($a);
            }
        };

        // 确定预览区域的位置, 分为: 'top' | 'bottom'
        var getPosition = $a => {
            var winHeight = pageVars.$window.height(),
                winScrollTop = pageVars.$window.scrollTop();
            var half = winHeight / 2;
            var anchorTop = $a.offset().top;

            return anchorTop > winScrollTop + half ? 'top' : 'bottom';
        };

        $(document).on('mouseenter', 'a', function () {
            dispatchLinkHovering(this, {
                link: ($a, tagHash) => PreviewActions.activatePreview({
                    url: previewStore.getUrlForTag(tagHash)
                }, getPosition($a)),
                tag: ($a, tagHash) => PreviewActions.activatePreview({
                    url: previewStore.getUrlForLink(tagHash)
                }, getPosition($a))
            });
        }).on('mouseleave', 'a', function () {
            dispatchLinkHovering(this, {
                both: $a => PreviewActions.deactivatePreview({}, getPosition($a))
            });
        })
    },
    initPreviewHovering() {
        $(document).on('mouseenter', '.preview', function () {
            PreviewActions.activatePreview();
        }).on('mouseleave', '.preview', function () {
            PreviewActions.deactivatePreview();
        });
    },

    initPageHashLoad() {
        pageMethods.scrollPage();

        pageVars.$body.addClass('hash-loaded');
    },
    initHashChanged() {
        pageVars.$window.on('hashchange', x => {
            pageMethods.scrollPage();
        });
    },

    initReact() {
        React.render(<PageApp />, document.getElementById('page-app'));

    },
    init() {
        pageVars.$body = $('body');

        // init event handlers
        this.initAnchorClicked();

        if (!isInPreview) {
            this.initAnchorHovering();
            this.initDocumentClicked();
            this.initPreviewHovering();

            // init React 模块
            this.initReact();
        } else {
            pageVars.$body.addClass('preview-page');
        }

        // init page hash loading
        this.initPageHashLoad();
        this.initHashChanged();
    }
};

$(x => initMethods.init());