// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html

cc.Class({
    extends: cc.Component,

    properties: {
        friendRankNode: {
            default: null,
            type: cc.Node
        },
        worldBtnDefault: {
            default: null,
            type: cc.SpriteFrame
        },
        worldBtnActive: {
            default: null,
            type: cc.SpriteFrame
        },
        friendBtnDefault: {
            default: null,
            type: cc.SpriteFrame
        },
        friendBtnActive: {
            default: null,
            type: cc.SpriteFrame
        },
        status: {
            get: function () {
                return this._status;
            },
            set: function (value) {
                this._status = value;
                if (this.friendBtn == null) return;
                if (value == 1) {
                    this.friendBtn.getComponent(cc.Sprite).spriteFrame = this.friendBtnActive;
                    this.worldBtn.getComponent(cc.Sprite).spriteFrame = this.worldBtnDefault;
                    this.worldContentNode.active = false;
                    this.friendContentNode.active = true;
                } else if (value == 2) {
                    this.friendBtn.getComponent(cc.Sprite).spriteFrame = this.friendBtnDefault;
                    this.worldBtn.getComponent(cc.Sprite).spriteFrame = this.worldBtnActive;
                    this.worldContentNode.active = true;
                    this.friendContentNode.active = false;
                }
            }
        },
        _viewitemTemp: {
            default: null
        },
        worldRankData: [],
        items: [],
        spacing: 10,
        spawnCount: 20,
        totalCount: 50,
        bufferZone: 800
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad: function () {
        this.PHB = cc.find("Canvas/PHB")
        this.rankNode = this.PHB.getChildByName("Rank")
        this.worldContentNode = this.rankNode.getChildByName('WorldContent')
        this.friendContentNode = this.rankNode.getChildByName('FriendContent')
        this.worldScrollView = this.worldContentNode.getChildByName("rankScrollView")
        this.worldScrollViewComponent = this.worldScrollView.getComponent(cc.ScrollView)

        this.content = this.worldScrollViewComponent.content
        if (this._viewitemTemp == null || this._viewitemTemp == 'undefined') {
            this._viewitemTemp = this.content.children[0];
            this.content.removeChild(this._viewitemTemp);
        }

        this.navNode = this.friendRankNode.getChildByName('Nav')
        this.friendBtn = this.navNode.getChildByName('FriendBtn');
        this.worldBtn = this.navNode.getChildByName('WorldBtn');
        this.friendBtnBg = this.navNode.getChildByName('FriendHoverBg');
        this.worldBtnBg = this.navNode.getChildByName('WorldHoverBg');

        this.status = this.status || 1;
        this.loading = 0;
        this.updateTimer = 0;
        this.updateInterval = 0.2;
        this.lastContentPosY = 0; // use this variable to detect if we are scrolling up or down
    },
    start() {
        this.initScrolll();
    },

    onEnable() {
        console.log('rank enable')
        this.initialize();
        this.getWorldRankData(() => {
            this.renderWorldData()
        })
    },
    initScrolll() {
        this.worldScrollView.on('scrolling', function () {
            if (this.loading) return;

            var maxOffset = this.worldScrollViewComponent.getMaxScrollOffset().y,
                offset = this.worldScrollViewComponent.getScrollOffset().y

            if (maxOffset - offset <= 300) {
                this.getWorldRankData()
            }
        }, this)
    },
    initialize() {
        this.items = [];
        this.worldRankData = [];
        this.content.removeAllChildren();
        this.worldScrollViewComponent.scrollToTop();
        this.content.height = this.totalCount * this._viewitemTemp.height + this.spacing * 2; // get total content height
    },
    getWorldRankData(callback) {
        this.loading = true;
        let startIndex = this.worldRankData.length
        for (var i = 0; i < 50; i++) {
            this.worldRankData.push({
                index: i + startIndex
            })
        }
        this.content.height = this.worldRankData.length * this._viewitemTemp.height + this.spacing * 2; // get total content height

        callback && callback()

        this.schedule(() => {
            this.loading = false
        }, 1);
    },
    renderWorldData() {
        for (let i = 0; i < this.spawnCount; ++i) { // spawn items, we only need to do this once
            let item = cc.instantiate(this._viewitemTemp);
            item.setPosition(0, -item.height * (0.5 + i) - this.spacing);
            this.updateNode(item, i)
            this.content.addChild(item);
            this.items.push(item);
            item.itemID = i;
        }
    },
    updateNode(node, index) {
        if (index <= 2) {
            node.getChildByName('ranknunbg' + index).active = true
            node.getChildByName('ranknum').active = false
        } else {
            node.getChildByName('ranknunbg0').active = false
            node.getChildByName('ranknunbg1').active = false
            node.getChildByName('ranknunbg2').active = false
            node.getChildByName('ranknum').active = true
        }
        node.getChildByName('ranknum').getComponent(cc.Label).string = index + 1
        node.getChildByName('username').getComponent(cc.Label).string = 'user' + (index + 1)
        node.getChildByName('CheckMark').active = ((index % 2) != 0);
        node.itemID = index
    },
    onFriendBtn() {
        if (this.status == 1) return;
        this.status = 1;
    },

    onWorldBtn() {
        if (this.status == 2) return;
        this.status = 2;
    },
    // get item position in scrollview's node space
    getPositionInView: function (item) {
        let worldPos = item.parent.convertToWorldSpaceAR(item.position);
        let viewPos = this.worldScrollView.convertToNodeSpaceAR(worldPos);
        return viewPos;
    },
    update(dt) {
        this.updateTimer += dt;
        if (this.updateTimer < this.updateInterval) return;
        this.updateTimer = 0;
        let items = this.items;
        let buffer = this.bufferZone;
        let isDown = this.content.y < this.lastContentPosY; // scrolling direction
        let offset = this._viewitemTemp.height * items.length;
        for (let i = 0; i < items.length; ++i) {
            let viewPos = this.getPositionInView(items[i]);
            if (isDown) {
                // if away from buffer zone and not reaching top of content
                if (viewPos.y < -buffer && items[i].y + offset < 0) {
                    items[i].setPositionY(items[i].y + offset);
                    let itemId = items[i].itemID - items.length; // update item id
                    this.updateNode(items[i], itemId)
                }
            } else {
                // if away from buffer zone and not reaching bottom of content
                if (viewPos.y > buffer && items[i].y - offset > -this.content.height) {
                    items[i].setPositionY(items[i].y - offset)
                    let itemId = items[i].itemID + items.length
                    this.updateNode(items[i], itemId)
                }
            }
        }

        this.lastContentPosY = this.worldScrollViewComponent.content.y;
    }
});
