"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const order_utils_1 = require("@0x/order-utils");
const types_1 = require("@0x/types");
const signWithWeb3Wrapper = (environment, order, signer) => __awaiter(this, void 0, void 0, function* () {
    const signedOrder = yield order_utils_1.signatureUtils.ecSignOrderAsync(environment.eth.currentProvider, order, signer);
    return signedOrder;
});
const signWithWallet = (environment, order, signer) => __awaiter(this, void 0, void 0, function* () {
    const orderHash = order_utils_1.orderHashUtils.getOrderHashHex(order);
    const signature = yield environment.wallet.signMessage(orderHash);
    const converted = order_utils_1.signatureUtils.convertECSignatureToSignatureHex(signature);
    const signedOrder = Object.assign({}, order, { signature: converted });
    return signedOrder;
});
// This is just a reference implementation
const signOrder = (environment, order, signer) => __awaiter(this, void 0, void 0, function* () {
    // const orderHash = orderHashUtils.getOrderHashHex(order);
    // const web3signature = await environment.eth.sign(
    //   orderHash,
    //   environment.wallet.address.toString(),
    // );
    const orderSigner = (signer || environment.wallet.address).toLowerCase();
    const signedOrder = environment.wallet.signMessage
        ? yield signWithWallet(environment, order, orderSigner)
        : yield signWithWeb3Wrapper(environment, order, orderSigner);
    const signatureTyped = signedOrder.makerAddress.toLowerCase() === orderSigner
        ? signedOrder
        : Object.assign({}, signedOrder, { signature: `${signedOrder.signature.slice(0, -1)}${types_1.SignatureType.PreSigned}` });
    return signatureTyped;
});
exports.signOrder = signOrder;
