const crypto = require('crypto-tx');
const hash_js = require('hash.js');
import buffer, { Zero } from 'somes/buffer';
import storage from 'somes/storage';
var privateKeyBytes = Zero;
var publicKeyBytes = Zero;
var publicKey = '';
var hex = storage.get('access_auth_key');
if (hex) {
    gen_access_key(buffer.from(hex, 'hex'));
}
else {
    genAccessKey();
}
function gen_access_key(privatekey) {
    privateKeyBytes = privatekey;
    publicKeyBytes = crypto.getPublic(privatekey, true);
    publicKey = '0x' + publicKeyBytes.toString('hex');
}
function genAccessKey() {
    gen_access_key(crypto.genPrivateKey());
    storage.set('access_auth_key', privateKeyBytes.toString('hex'));
}
class H5Signer {
    setExtra(extra) {
        this._extra = extra;
    }
    sign(url, data) {
        var st = Date.now();
        var fuzz_key = '0a37eb70c1737777bc111d03af4fcd091bc6d913baa2f90316511c61943dbce2';
        var sha256 = hash_js.sha256();
        if (data) {
            sha256.update(data);
        }
        url = url.replace(/^.+\/service-api\//, '/service-api/');
        sha256.update(st + fuzz_key + url);
        var message = buffer.from(sha256.digest());
        var { signature, recovery } = crypto.sign(message, privateKeyBytes);
        var sign = buffer.alloc(65);
        signature.copy(sign);
        sign[64] = recovery;
        return Object.assign({
            st, sign: sign.toString('base64'),
        }, this._extra);
    }
}
const signer = new H5Signer();
export default {
    genAccessKey,
    signer,
    get publicKeyBytes() { return publicKeyBytes; },
    get publicKey() { return publicKey; },
};
