"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
var LoopComponent = (function (_super) {
    __extends(LoopComponent, _super);
    function LoopComponent() {
        var _this = _super.call(this) || this;
        _this.onceInfo = { width: 0, height: 0, count: 0 };
        _this.loopInfo = { width: 0, height: 0, count: 0 };
        _this.parts = [];
        return _this;
    }
    LoopComponent.prototype.setup = function (parts, info) {
        var _this = this;
        parts.forEach(function (item, index) {
            var part;
            if (typeof item == 'string') {
                part = new engine.Sprite(utils_1.getTextureByName(item));
            }
            else if (item instanceof engine.Texture) {
                part = new engine.Sprite(item);
            }
            else {
                part = item;
            }
            _this.addChild(part);
            _this.parts.push(part);
            if (index == 0) {
                info.width = part.width;
                info.height = part.height;
            }
        });
        info.count = parts.length;
        this.setViewport(0, 0);
    };
    LoopComponent.prototype.changeBg = function (changName) {
        this.parts.forEach(function (item, index) {
            item.texture = utils_1.getTextureByName(changName);
        });
    };
    LoopComponent.prototype.setupLoop = function (resArr) {
        this.setup(resArr, this.loopInfo);
    };
    LoopComponent.prototype.setViewport = function (x, y) {
        if (y === void 0) { y = 0; }
        var sizeField = y == 0 ? 'width' : 'height';
        var posField = y == 0 ? 'x' : 'y';
        var pos = y == 0 ? x : y;
        var index;
        var onceSize = this.onceInfo[sizeField];
        var onceCount = this.onceInfo.count;
        var loopCount = this.loopInfo.count;
        var loopSize = this.loopInfo[sizeField];
        index = onceSize == 0 ? -1 : Math.floor(pos / onceSize);
        if (index < 0 || index >= onceCount) {
            var loopIndex = Math.floor((pos - onceCount * onceSize) / this.loopInfo[sizeField]);
            index = onceCount + loopIndex;
        }
        var formerIndex = index < onceCount ? index : (index) % loopCount + onceCount;
        var latterIndex = index < onceCount ? index + 1 : (index - onceCount + 1) % loopCount + onceCount;
        var former = this.parts[formerIndex];
        var latter = this.parts[latterIndex];
        if (!former || !latter) {
            console.log(formerIndex, latterIndex);
        }
        former[posField] = -(pos - loopSize * (index < onceCount ? index : index - onceCount) - (index < onceCount ? 0 : onceCount * onceSize));
        latter[posField] = former.x + (index < onceCount ? onceSize : loopSize);
    };
    return LoopComponent;
}(engine.Container));
exports.LoopComponent = LoopComponent;
