// Copyright (c) 2017, 2021 Pieter Wuille
//
// 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 { BitcoinBech32 } from "./bech32.js";
import { OperationResult, opFixedSuccess, opKnownFailure } from "./operation.js";
import { BtAddrString } from "./payto.js";

function convertbits(
  data: Array<number>,
  frombits: number,
  tobits: number,
  pad: boolean,
): Array<number> | null {
  let acc = 0;
  let bits = 0;
  const ret: Array<number> = [];
  const maxv = (1 << tobits) - 1;
  for (let p = 0; p < data.length; ++p) {
    const value = data[p];
    if (value < 0 || value >> frombits !== 0) {
      return null;
    }
    acc = (acc << frombits) | value;
    bits += frombits;
    while (bits >= tobits) {
      bits -= tobits;
      ret.push((acc >> bits) & maxv);
    }
  }
  if (pad) {
    if (bits > 0) {
      ret.push((acc << (tobits - bits)) & maxv);
    }
  } else if (bits >= frombits || (acc << (tobits - bits)) & maxv) {
    return null;
  }
  return ret;
}

export namespace BitcoinSewgit {
  export enum BitcoinSewgitParseError {
    /**
     * Input data is wrong
     */
    INVALID_DATA = "invalid-data",
    /**
     * Generic parsing problem
     */
    DECODING_PROBLEM = "decoding-problem",
  }
  export function decode(
    addr: string,
    enc?: BitcoinBech32.Encodings,
  ): OperationResult<
    { version: number; program: Array<number> },
    BitcoinBech32.BitcoinParseError | BitcoinSewgitParseError
  > {
    const decResp = BitcoinBech32.decode(addr, enc);
    if (decResp.type === "fail") {
      return decResp;
    }
    const { body: dec } = decResp;

    if (dec.data.length < 1 || dec.data[0] > 16) {
      return opKnownFailure(BitcoinSewgitParseError.INVALID_DATA);
    }
    const res = convertbits(dec.data.slice(1), 5, 8, false);
    if (res === null || res.length < 2 || res.length > 40) {
      return opKnownFailure(BitcoinSewgitParseError.DECODING_PROBLEM);
    }
    if (dec.data[0] === 0 && res.length !== 20 && res.length !== 32) {
      return opKnownFailure(BitcoinSewgitParseError.DECODING_PROBLEM);
    }
    if (dec.data[0] === 0 && enc === BitcoinBech32.Encodings.BECH32) {
      return opKnownFailure(BitcoinSewgitParseError.DECODING_PROBLEM);
    }
    if (dec.data[0] !== 0 && enc === BitcoinBech32.Encodings.BECH32M) {
      return opKnownFailure(BitcoinSewgitParseError.DECODING_PROBLEM);
    }
    return opFixedSuccess({ version: dec.data[0], program: res });
  }

  export function encode(
    hrp: string,
    version: number,
    program: Array<number>,
  ) {
    const enc =
      version > 0
        ? BitcoinBech32.Encodings.BECH32M
        : BitcoinBech32.Encodings.BECH32;
    const bits = convertbits(program, 8, 5, true);
    if (!bits) {
      return opKnownFailure(BitcoinSewgitParseError.INVALID_DATA);
    }
    const ret = BitcoinBech32.encode(hrp, [version].concat(bits), enc);
    return opFixedSuccess(ret);
  }
}
