// 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 { assertUnreachable } from "./errors.js";
import { opFixedSuccess, opKnownFailure } from "./operation.js";
import { BtAddrString } from "./payto.js";

var CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
var GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];

function polymod(values: Array<number>): number {
  var chk = 1;
  for (var p = 0; p < values.length; ++p) {
    var top = chk >> 25;
    chk = ((chk & 0x1ffffff) << 5) ^ values[p];
    for (var i = 0; i < 5; ++i) {
      if ((top >> i) & 1) {
        chk ^= GENERATOR[i];
      }
    }
  }
  return chk;
}

function hrpExpand(hrp: string): Array<number> {
  const ret: Array<number> = [];
  for (let p = 0; p < hrp.length; ++p) {
    ret.push(hrp.charCodeAt(p) >> 5);
  }
  ret.push(0);
  for (let p = 0; p < hrp.length; ++p) {
    ret.push(hrp.charCodeAt(p) & 31);
  }
  return ret;
}

function getEncodingConst(enc: BitcoinBech32.Encodings): number {
  switch (enc) {
    case BitcoinBech32.Encodings.BECH32:
      return 1;
    case BitcoinBech32.Encodings.BECH32M:
      return 0x2bc830a3;
  
    default: {
      assertUnreachable(enc);
    }
  }
}

function verifyChecksum(
  hrp: string,
  data: Array<number>,
  enc: BitcoinBech32.Encodings,
): boolean {
  return polymod(hrpExpand(hrp).concat(data)) === getEncodingConst(enc);
}

function createChecksum(
  hrp: string,
  data: Array<number>,
  enc: BitcoinBech32.Encodings,
): Array<number> {
  const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
  const mod = polymod(values) ^ getEncodingConst(enc);
  const ret: Array<number> = [];
  for (let p = 0; p < 6; ++p) {
    ret.push((mod >> (5 * (5 - p))) & 31);
  }
  return ret;
}

export namespace BitcoinBech32 {

  export enum Encodings {
    BECH32 = "bech32",
    BECH32M = "bech32m",
  };

  export function encode(
    hrp: string,
    data: Array<number>,
    enc: Encodings,
  ): BtAddrString {
    var combined = data.concat(createChecksum(hrp, data, enc));
    var ret = hrp + "1";
    for (var p = 0; p < combined.length; ++p) {
      ret += CHARSET.charAt(combined[p]);
    }
    return ret as BtAddrString;
  }

  export enum BitcoinParseError {
    /**
     * Charset can only be from BECH32
     */
    WRONG_CHARSET,
    /**
     * All uppercased or all lowercased
     */
    MIXING_UPPER_AND_LOWER,
    /**
     * Separator is a '1' between addr and addrtype
     */
    MISSING_HRP,
    /**
     * Should be less or equal to 90 chars
     */
    TOO_LONG,
    /**
     * Addr should be greather or equal to 6 chars
     */
    TOO_SHORT,
    WRONG_CHECKSUM,
  }

  export function decode(
    bechString: string,
    enc?: Encodings,
  ) {
    let p;
    let has_lower = false;
    let has_upper = false;
    for (p = 0; p < bechString.length; ++p) {
      if (bechString.charCodeAt(p) < 33 || bechString.charCodeAt(p) > 126) {
        return opKnownFailure(BitcoinParseError.WRONG_CHARSET);
      }
      if (bechString.charCodeAt(p) >= 97 && bechString.charCodeAt(p) <= 122) {
        has_lower = true;
      }
      if (bechString.charCodeAt(p) >= 65 && bechString.charCodeAt(p) <= 90) {
        has_upper = true;
      }
    }
    if (has_lower && has_upper) {
      return opKnownFailure(BitcoinParseError.MIXING_UPPER_AND_LOWER);
    }
    bechString = bechString.toLowerCase();
    const pos = bechString.lastIndexOf("1");
    if (pos < 1) {
      return opKnownFailure(BitcoinParseError.MISSING_HRP);
    }
    if (pos + 7 > bechString.length) {
      return opKnownFailure(BitcoinParseError.TOO_SHORT);
    }
    if (bechString.length > 90) {
      return opKnownFailure(BitcoinParseError.TOO_LONG);
    }
    const hrp = bechString.substring(0, pos);
    var data: Array<number> = [];
    for (p = pos + 1; p < bechString.length; ++p) {
      var d = CHARSET.indexOf(bechString.charAt(p));
      if (d === -1) {
        return opKnownFailure(BitcoinParseError.WRONG_CHARSET);
      }
      data.push(d);
    }
    if (enc && !verifyChecksum(hrp, data, enc)) {
      return opKnownFailure(BitcoinParseError.WRONG_CHECKSUM);
    }
    return opFixedSuccess({ hrp, data: data.slice(0, data.length - 6) });
  }
}
