/********************************************************************
 * @author:      Kaven
 * @email:       kaven@wuwenkai.com
 * @website:     http://kavenblog.com
 * @file:        [Kaven-Basic] /src/libs/BitString.ts
 * @create:      2018-08-30 16:07:15.084
 * @modify:      2019-04-12 11:15:18.187
 * @version:     1.1.20
 * @times:       61
 * @lines:       422
 * @copyright:   Copyright © 2018 Kaven. All Rights Reserved.
 * @description: [description]
 * @license:
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ********************************************************************/
import { BitStringType } from "./Enums";
import { Strings } from "./Strings";
/**
 * @version 1.0.0
 * @since 1.0.5
 */
var BitString = /** @class */ (function () {
    function BitString(initialValue, type) {
        if (type === void 0) { type = BitStringType.BIN; }
        if (!initialValue) {
            this.binStr = Strings.Empty;
            return;
        }
        if (typeof initialValue === "number") {
            if (initialValue > Number.MAX_SAFE_INTEGER) {
                throw new Error("Initial value is too big: " + initialValue + " > " + Number.MAX_SAFE_INTEGER);
            }
            initialValue = initialValue.toString(2);
        }
        var radix;
        if (typeof type === "number") {
            radix = type;
        }
        else {
            switch (type) {
                case BitStringType.BIN:
                    radix = 2;
                    break;
                case BitStringType.HEX:
                    radix = 16;
                    break;
                default:
                    throw new Error("Invalid BitStringType: " + type);
            }
        }
        if (radix === 2) {
            this.binStr = initialValue;
        }
        else if (radix === 16) {
            var temp = Strings.Empty;
            for (var _i = 0, initialValue_1 = initialValue; _i < initialValue_1.length; _i++) {
                var val = initialValue_1[_i];
                temp += parseInt(val, radix).toString(2).padStart(4, "0");
            }
            this.binStr = temp;
        }
        else {
            // to be Refined
            this.binStr = parseInt(initialValue, radix).toString(2);
        }
    }
    Object.defineProperty(BitString.prototype, "Length", {
        get: function () {
            return this.binStr.length;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BitString.prototype, "HEX", {
        get: function () {
            return this.toString();
        },
        enumerable: true,
        configurable: true
    });
    BitString.FromBytes = function () {
        var bytes = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            bytes[_i] = arguments[_i];
        }
        var bin = Strings.Empty;
        for (var _a = 0, bytes_1 = bytes; _a < bytes_1.length; _a++) {
            var byte = bytes_1[_a];
            bin += byte.toString(2).padStart(8, "0");
        }
        return new BitString(bin);
    };
    BitString.Initialize2d = function (x, y) {
        return new Array(x).fill(new BitString()).map(function () { return new Array(y).fill(new BitString()); });
    };
    /**
     * Set some bit
     * @param offset right to left, start from 1
     * @param val true or false
     */
    BitString.prototype.SetBit = function (offset, val) {
        if (offset < 1) {
            throw new Error("Unexpected offset: " + offset);
        }
        var value = val ? "1" : "0";
        var index = this.Length - offset;
        if (index >= 0) {
            this.binStr = this.binStr.ReplaceAt(index, value);
        }
        else {
            this.binStr = value + this.binStr.padStart(offset - 1, "0");
        }
        return this;
    };
    /**
     *
     * @param offset
     * @param defaultVal
     * @since 1.1.20
     * @version 2019-04-01
     */
    BitString.prototype.GetBit = function (offset, defaultVal) {
        if (defaultVal === void 0) { defaultVal = false; }
        if (offset < 1) {
            throw new Error("Unexpected offset: " + offset);
        }
        var index = this.Length - offset;
        if (index < 0) {
            return defaultVal;
        }
        return this.binStr[index] === "1";
    };
    BitString.prototype.AnyBit = function () {
        return this.binStr.includes("1");
    };
    BitString.prototype.toString = function (type, trim) {
        if (type === void 0) { type = BitStringType.HEX; }
        if (trim === void 0) { trim = false; }
        if (this.binStr.length === 0) {
            return Strings.Empty;
        }
        switch (type) {
            case BitStringType.BIN:
                return this.binStr;
            case BitStringType.HEX:
                var array = this.binStr.SplitByN(4);
                var hex = array.map(function (p) { return parseInt(p, 2).toString(16); }).join(Strings.Empty);
                if (trim) {
                    hex = hex.TrimStart("0", hex.length);
                }
                if (hex === Strings.Empty) {
                    return "0";
                }
                return hex;
            default:
                throw new Error("Invalid BitStringType: " + type);
        }
    };
    /**
     *
     * @param val
     * @since 1.1.20
     * @version 2019-04-01
     */
    BitString.prototype.Add = function (val) {
        var result = Strings.Empty;
        var carry = false;
        var i = 1;
        var j = 1;
        while (i <= this.Length || j <= val.Length || carry) {
            var a = this.GetBit(i);
            var b = val.GetBit(j);
            if (carry) {
                if (a === b) {
                    result = "1" + result;
                    carry = a;
                }
                else {
                    result = "0" + result;
                    carry = true;
                }
            }
            else {
                if (a === b) {
                    result = "0" + result;
                    carry = a;
                }
                else {
                    result = "1" + result;
                    carry = false;
                }
            }
            // Move to next digits
            i++;
            j++;
        }
        return new BitString(result);
    };
    /**
     *
     * @param val
     * @since 1.1.20
     * @version 2019-04-01
     */
    BitString.prototype.AND = function (val) {
        if (typeof val === "number") {
            val = new BitString(val);
        }
        if (this.Length > val.Length) {
            val.SetLength(this.Length);
        }
        else if (this.Length < val.Length) {
            this.SetLength(val.Length);
        }
        var result = Strings.Empty;
        for (var i = 0; i < this.Length; i++) {
            result += ((this.binStr[i] === "1" && val.binStr[i]) === "1" ? "1" : "0");
        }
        return new BitString(result);
    };
    /**
     *
     * @param val
     * @since 1.1.20
     * @version 2019-04-01
     */
    BitString.prototype.OR = function (val) {
        if (typeof val === "number") {
            val = new BitString(val);
        }
        var result = Strings.Empty;
        var i = 1;
        while (i <= this.Length || i <= val.Length) {
            var a = this.GetBit(i);
            var b = val.GetBit(i);
            if (a || b) {
                result = "1" + result;
            }
            else {
                result = "0" + result;
            }
            i++;
        }
        return new BitString(result);
    };
    /**
     *
     * @since 1.1.20
     * @version 2019-04-01
     */
    BitString.prototype.NOT = function () {
        var result = Strings.Empty;
        for (var _i = 0, _a = this.binStr; _i < _a.length; _i++) {
            var c = _a[_i];
            result += c === "0" ? "1" : "0";
        }
        return new BitString(result);
    };
    /**
     *
     * @param val
     * @since 1.1.20
     * @version 2019-04-01
     */
    BitString.prototype.XOR = function (val) {
        if (typeof val === "number") {
            val = new BitString(val);
        }
        if (this.Length > val.Length) {
            val.SetLength(this.Length);
        }
        else if (this.Length < val.Length) {
            this.SetLength(val.Length);
        }
        var result = Strings.Empty;
        for (var i = 0; i < this.Length; i++) {
            result += this.binStr[i] !== val.binStr[i] ? "1" : "0";
        }
        return new BitString(result);
    };
    BitString.prototype.LeftShift = function (n) {
        var right = "0".repeat(n);
        return new BitString(this.binStr + right);
    };
    BitString.prototype.RightShift = function (n) {
        var left = "0".repeat(n);
        if (this.Length < n) {
            return new BitString(left);
        }
        else {
            return new BitString(left + this.binStr.substring(0, this.Length - n));
        }
    };
    BitString.prototype.LeftRotate = function (n, bits) {
        if (bits === void 0) { bits = 64; }
        this.SetLength(bits);
        // return this.LeftShift(n).OR(this.RightShift(bits - n)).SetLength(bits);
        return new BitString(this.binStr.substring(n) + this.binStr.substring(0, n));
    };
    BitString.prototype.RightRotate = function (n, bits) {
        if (bits === void 0) { bits = 64; }
        this.SetLength(bits);
        // return this.RightShift(n).OR(this.LeftShift(bits - n)).SetLength(bits);
        return this.LeftRotate(bits - n);
    };
    BitString.prototype.ToNumber = function () {
        return parseInt(this.binStr, 2);
    };
    BitString.prototype.ToBytes = function (bits) {
        if (bits) {
            this.SetLength(bits);
        }
        var byteArray = [];
        var hexArray = this.HEX.SplitByN(2);
        for (var _i = 0, hexArray_1 = hexArray; _i < hexArray_1.length; _i++) {
            var hex = hexArray_1[_i];
            byteArray.push(parseInt(hex, 16));
        }
        return byteArray;
    };
    BitString.prototype.Reflect = function (bits) {
        if (bits) {
            this.SetLength(bits);
        }
        return new BitString(this.binStr.Reverse());
    };
    BitString.prototype.SetLength = function (bits) {
        if (this.Length > bits) {
            this.binStr = this.binStr.substring(this.Length - bits);
        }
        else if (this.AND.length < bits) {
            this.binStr = this.binStr.padStart(bits, "0");
        }
        return this;
    };
    BitString.prototype.Clone = function () {
        return new BitString(this.binStr);
    };
    BitString.prototype.Swap = function (bytes) {
        if (bytes === void 0) { bytes = 8; }
        this.SetLength(bytes * 8);
        var result = this.binStr.SplitByN(8).reverse().join(Strings.Empty);
        return new BitString(result);
    };
    return BitString;
}());
export { BitString };
//# sourceMappingURL=BitString.js.map