import { __assign, __extends, __rest } from "tslib";
import React, { Component } from 'react';
var IotCountdown = /** @class */ (function (_super) {
    __extends(IotCountdown, _super);
    function IotCountdown(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            timeLeft: Number.parseInt(props.time)
        };
        return _this;
    }
    IotCountdown.prototype.tick = function () {
        var _this = this;
        var _a = this.props, onComplete = _a.onComplete, onTick = _a.onTick;
        var timeLeft = this.state.timeLeft;
        if (timeLeft <= 0) {
            onComplete && onComplete();
            if (this.timer) {
                clearTimeout(this.timer);
                this.timer = null;
            }
        }
        else {
            this.timer = setTimeout(function () {
                var newTimeLeft = timeLeft - 1000;
                onTick && onTick(newTimeLeft);
                _this.setState({ timeLeft: newTimeLeft });
                _this.tick();
            }, 1000);
        }
    };
    IotCountdown.prototype.componentDidMount = function () {
        if (this.state.timeLeft) {
            this.tick();
        }
    };
    IotCountdown.prototype.componentWillUnmount = function () {
        if (this.timer) {
            clearTimeout(this.timer);
        }
    };
    IotCountdown.prototype.render = function () {
        var _a = this.props, time = _a.time, text = _a.text, finishText = _a.finishText, onComplete = _a.onComplete, onTick = _a.onTick, rest = __rest(_a, ["time", "text", "finishText", "onComplete", "onTick"]);
        var timeLeft = this.state.timeLeft;
        var showNumber = timeLeft / 1000;
        return (React.createElement("div", __assign({}, rest),
            timeLeft <= 0 ? finishText ? finishText : text : text,
            timeLeft ? React.createElement("span", null, "(" + showNumber + "s)") : null));
    };
    return IotCountdown;
}(Component));
IotCountdown.defaultProps = {
    time: 10000
};
export default IotCountdown;
