import Reflux from 'reflux';
import PreviewActions from './PreviewActions.jsx';

import _ from 'lodash';

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

import {constants} from '../constants.jsx';
import {urlTypes} from '../constants.jsx';

var previewStore = Reflux.createStore({
    listenables: [PreviewActions],

    onActivatePreview(linkOpts, previewPosition) {
        this.preTransitionPreview('hover', linkOpts, previewPosition);
    },

    onDeactivatePreview(previewPosition) {
        this.preTransitionPreview('leave', null, previewPosition);
    },

    onClickOnPage() {
        this._store.isShown = false;
        this.clearCounting();
        this.update();
    },

    onClosePreview() {

    },

    getUrlForLink(tagHash) {
        return util.getSpecialUrl(urlTypes.composing, {
            tag: tagHash
        });
    },

    getUrlForTag(tagHash) {
        var store = this._store;
        var tag = store.tags[tagHash];

        if (tag) {
            // shit, 在firefox中, 同src在嵌套iframe中显示有问题 @[  学习  ]{vdsvz_te9nw8xz_iht7pmsz}@
            return util.getWikiPageUrl({
                path: tag.path,
                isPreview: true,
                hash: {
                    tag: tagHash
                }
            });
        } else {
            return util.getSpecialUrl(urlTypes.p404);
        }
    },

    changePreviewUrlWorker: null,
    changePreviewUrl: _.debounce(function (url) {
        if (url) {
            this._store.previewUrl = url;
            this.update();
        }
    }, 250),

    previewCountdownTimer: null,
    preTransitionPreview(type, linkOpts, previewPosition) {
        linkOpts = linkOpts || {};
        // 无论如何, 我们要清理掉preview
        this.clearCounting();

        if (type == 'hover') {
            this.changePreviewUrlWorker = this.changePreviewUrl(linkOpts.url);
            if (this._store.isShown) return;
        } else if (type == 'leave') {
            this.changePreviewUrlWorker && this.changePreviewUrlWorker.cancel();
            if (!this._store.isShown) return;
        }

        // hover在preview上不应该触发窗口打开
        if (!previewPosition && !this._store.isShown) {
            return;
        }

        if (!this._store.isShown) {
            this._store.previewPositionClass = previewPosition;
            this._store.isCounting = true;
        }

        var startTime = new Date().getTime();

        var maxTime = !this._store.isShown ? constants.previewShowDelayInMilli : constants.previewHideDelayInMilli;
        this._store.previewCountdown = maxTime / 1000;
        this.update();

        // 预览的倒计时开始
        this.previewCountdownTimer = setInterval(x => {
            var currTime = new Date().getTime();

            var delta = currTime - startTime;

            this._store.previewCountdown = Math.floor((maxTime - delta) / 100) / 10;
            console.log('count down', this._store.previewCountdown, delta);
            this.update();

            // 当倒计时结束事
            if (delta >= constants.previewShowDelayInMilli) {
                this._store.previewCountdown = 0;

                // 显示或隐藏
                this._store.isShown = !this._store.isShown;
                this.update();
                this.transitionPreview();
            }
        }, 50);
    },
    transitionPreview() {
        this.clearCounting();
    },
    clearCounting() {
        if (this._store.isCounting) {
            this._store.isCounting = false;
            this.update();
        }

        clearInterval(this.previewCountdownTimer);
    },
    cancelPreview() {
        this.clearCounting();
    },

    update(store) {
        if (store) {
            this._store = store;
        }

        this.trigger(this._store);
    },
    _store: {},
    init() {
        this.initTags();

        this._store = {
            previewUrl: '',
            previewCountdown: 0.8,
            isShown: false,
            tags: {},
        }
    },
    initTags() {
        dataAccess.getTags()
            .done(tags => this._store.tags = tags);
    },
    getInitialState() {
        return this._store;
    }
});

export default previewStore;