<commit_before>// @flow
/*jshint esversion: 6 */
/*jslint node: true */
"use strict";

const {ipcRenderer} = require("electron");
// FIXME: unused List
const {List} = require("immutable");
const Qrcode = require("qrcode");

function logIpc(msgType) {
    ipcRenderer.on(msgType, (...args) => {
        console.log(`IPC Message: ${msgType}, Args:`);
        for (let i = 0; i < args.length; i++)
            console.log(args[i]);
    });
}

// sed -r -n "/\.send/{s/.*send\("([^"]+)".*/logIpc("\1");/p}" main.js|sort -u
logIpc("call-get-wallets");
logIpc("check-login-response");
logIpc("generate-wallet-response");
logIpc("get-settings-response");
logIpc("get-transaction-update");
logIpc("get-wallet-by-name-response");
//logIpc("get-wallets-response");
logIpc("refresh-wallet-response");
//logIpc("rename-wallet-response");
logIpc("render-qr-code");
logIpc("save-settings-response");
logIpc("send-finish");
logIpc("show-notification-response");
logIpc("update-wallet-balance");
logIpc("verify-login-response");
logIpc("write-login-response");
logIpc("zz-get-wallets");

let addrListNode = document.getElementById("addrList");
const txListNode = document.getElementById("txList");
const totalBalanceNode = document.getElementById("totalBalance");
const depositTabButton = document.getElementById("depositTabButton");
const depositToButton = document.getElementById("depositToButton");
const depositToAddrInput = document.getElementById("depositToAddr");
const depositAmountInput = document.getElementById("depositAmount");
const depositMsg = document.getElementById("depositMsg");
const depositQrcodeImage = document.getElementById("depositQrcodeImg");
const withdrawTabButton = document.getElementById("withdrawTabButton");
// FIXME: withdrawAvailBalanceNode unused
const withdrawAvailBalanceNode = document.getElementById("withdrawAvailBalance");
const withdrawFromButton = document.getElementById("withdrawFromButton");
const withdrawFromAddrInput = document.getElementById("withdrawFromAddr");
const withdrawToButton = document.getElementById("withdrawToButton");
const withdrawToAddrInput = document.getElementById("withdrawToAddr");
const withdrawAmountInput = document.getElementById("withdrawAmount");
const withdrawFeeInput = document.getElementById("withdrawFee");
const withdrawMsg = document.getElementById("withdrawMsg");
const withdrawButton = document.getElementById("withdrawButton");
const withdrawStatusTitleNode = document.getElementById("withdrawStatusTitle");
const withdrawStatusBodyNode = document.getElementById("withdrawStatusBody");

const refreshTimeout = 300;
let refreshTimer;
let showZeroBalances = false;
let depositQrcodeTimer;
const myAddrs = new Set();

// ---------------------------------------------------------------------------------------------------------------------
// IPC
ipcRenderer.on("get-wallets-response", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    clearChildNodes(addrListNode);
    clearChildNodes(txListNode);
    // TODO: sort like txs
    addAddresses(msg.wallets);
    addTransactions(msg.transactions);
    setTotalBalance(msg.total);
    scheduleRefresh();
});

ipcRenderer.on("update-wallet-balance", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    setAddressBalance(msg.wallet, msg.balance);
    setTotalBalance(msg.total);
});

ipcRenderer.on("get-transaction-update", (event, msgStr) => {
    const txObj = JSON.parse(msgStr);
    txObj.amount = parseFloat(txObj.amount);
    addTransactions([txObj], true);
});

ipcRenderer.on("refresh-wallet-response", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    scheduleRefresh();
});

ipcRenderer.on("send-finish", (event, result, msg) =>
    updateWithdrawalStatus(result, msg));

ipcRenderer.on("rename-wallet-response", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    setAddressName(msg.addr, msg.newname);
});

ipcRenderer.on("generate-wallet-response", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    addNewAddress(msg.addr);
});

window.addEventListener("load", initWallet);

// FUNCTIONS
function checkResponse(resp) {
    if (resp.response !== "OK") {
        console.error(resp);
        throw new Error("Failed response");
    }
}

// Expects a balance node with one balanceAmount child node
function setBalanceText(balanceNode, balance) {
    const balanceAmountNode = balanceNode.firstElementChild;
    balanceAmountNode.textContent = formatBalance(balance);
    if (balance > 0)
        balanceNode.classList.add("positive");
    else
        balanceNode.classList.remove("positive");
}

function setFiatBalanceText(balanceZEN) {
    const totalBalanceFiatNode = document.getElementById("totalBalanceFiat");
    const balanceFiatAmountNode = totalBalanceFiatNode.firstElementChild;
    const LastUpdateTimeNode = document.getElementById("LastUpdateTime");
    let fiat = 'USD' //FIXME: Get from settings the desired fiat currency
    zenToFiat(fiat).then( function(ZENPrice){
      //console.log(ZENPrice);
      const now = new Date();
      // View the output
      console.log(now);
      let balance = (balanceZEN) * ZENPrice;
      //console.log(balance);
      balanceFiatAmountNode.textContent = formatFiatBalance(balance) + " " + fiat;
      LastUpdateTimeNode.textContent = now;

    });
}

function zenToFiat(fiat){
  const fetch = require("node-fetch");
  let BASE_API_URL = 'https://api.coinmarketcap.com/v1//ticker'
  let API_URL = BASE_API_URL + '/zencash/?convert='+ fiat;

  console.log("GET " + API_URL);
  return fetch(API_URL).then( function(resp){
      console.log(`GET ${API_URL} done, status: ${resp.status} ${resp.statusText}`);
      if (!resp.ok)
          throw new Error(`HTTP GET status: ${resp.status} ${resp.statusText}, URL: ${API_URL}`);
      return resp.json()
  }).then( function(responseAsJson) {
    console.log(responseAsJson);
    //console.log(parseFloat(responseAsJson[0].price_usd));
    //console.log(("responseAsJson[0].price_"+fiat.toLowerCase()));
    return parseFloat(eval("responseAsJson[0].price_"+fiat.toLowerCase()));
  });
};

function createAddrItem(addrObj) {
    const addrItem = cloneTemplate("addrItemTemplate");

    addrItem.dataset.addr = addrObj.addr;
    addrItem.dataset.name = addrObj.name || '';<commit_msg>Add PGP key. (try again)<commit_after>// @flow
/*jshint esversion: 6 */
/*jslint node: true */
"use strict";

const {ipcRenderer} = require("electron");
// FIXME: unused List
const {List} = require("immutable");
const Qrcode = require("qrcode");

function logIpc(msgType) {
    ipcRenderer.on(msgType, (...args) => {
        console.log(`IPC Message: ${msgType}, Args:`);
        for (let i = 0; i < args.length; i++)
            console.log(args[i]);
    });
}

// sed -r -n "/\.send/{s/.*send\("([^"]+)".*/logIpc("\1");/p}" main.js|sort -u
logIpc("call-get-wallets");
logIpc("check-login-response");
logIpc("generate-wallet-response");
logIpc("get-settings-response");
logIpc("get-transaction-update");
logIpc("get-wallet-by-name-response");
//logIpc("get-wallets-response");
logIpc("refresh-wallet-response");
//logIpc("rename-wallet-response");
logIpc("render-qr-code");
logIpc("save-settings-response");
logIpc("send-finish");
logIpc("show-notification-response");
logIpc("update-wallet-balance");
logIpc("verify-login-response");
logIpc("write-login-response");
logIpc("zz-get-wallets");

let addrListNode = document.getElementById("addrList");
const txListNode = document.getElementById("txList");
const totalBalanceNode = document.getElementById("totalBalance");
const depositTabButton = document.getElementById("depositTabButton");
const depositToButton = document.getElementById("depositToButton");
const depositToAddrInput = document.getElementById("depositToAddr");
const depositAmountInput = document.getElementById("depositAmount");
const depositMsg = document.getElementById("depositMsg");
const depositQrcodeImage = document.getElementById("depositQrcodeImg");
const withdrawTabButton = document.getElementById("withdrawTabButton");
// FIXME: withdrawAvailBalanceNode unused
const withdrawAvailBalanceNode = document.getElementById("withdrawAvailBalance");
const withdrawFromButton = document.getElementById("withdrawFromButton");
const withdrawFromAddrInput = document.getElementById("withdrawFromAddr");
const withdrawToButton = document.getElementById("withdrawToButton");
const withdrawToAddrInput = document.getElementById("withdrawToAddr");
const withdrawAmountInput = document.getElementById("withdrawAmount");
const withdrawFeeInput = document.getElementById("withdrawFee");
const withdrawMsg = document.getElementById("withdrawMsg");
const withdrawButton = document.getElementById("withdrawButton");
const withdrawStatusTitleNode = document.getElementById("withdrawStatusTitle");
const withdrawStatusBodyNode = document.getElementById("withdrawStatusBody");

const refreshTimeout = 300;
let refreshTimer;
let showZeroBalances = false;
let depositQrcodeTimer;
const myAddrs = new Set();

// ---------------------------------------------------------------------------------------------------------------------
// IPC
ipcRenderer.on("get-wallets-response", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    clearChildNodes(addrListNode);
    clearChildNodes(txListNode);
    // TODO: sort like txs
    addAddresses(msg.wallets);
    addTransactions(msg.transactions);
    setTotalBalance(msg.total);
    scheduleRefresh();
});

ipcRenderer.on("update-wallet-balance", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    setAddressBalance(msg.wallet, msg.balance);
    setTotalBalance(msg.total);
});

ipcRenderer.on("get-transaction-update", (event, msgStr) => {
    const txObj = JSON.parse(msgStr);
    txObj.amount = parseFloat(txObj.amount);
    addTransactions([txObj], true);
});

ipcRenderer.on("refresh-wallet-response", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    scheduleRefresh();
});

ipcRenderer.on("send-finish", (event, result, msg) =>
    updateWithdrawalStatus(result, msg));

ipcRenderer.on("rename-wallet-response", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    setAddressName(msg.addr, msg.newname);
});

ipcRenderer.on("generate-wallet-response", (event, msgStr) => {
    const msg = JSON.parse(msgStr);
    checkResponse(msg);
    addNewAddress(msg.addr);
});

window.addEventListener("load", initWallet);

// FUNCTIONS
function checkResponse(resp) {
    if (resp.response !== "OK") {
        console.error(resp);
        throw new Error("Failed response");
    }
}

// Expects a balance node with one balanceAmount child node
function setBalanceText(balanceNode, balance) {
    const balanceAmountNode = balanceNode.firstElementChild;
    balanceAmountNode.textContent = formatBalance(balance);
    if (balance > 0)
        balanceNode.classList.add("positive");
    else
        balanceNode.classList.remove("positive");
}

function setFiatBalanceText(balanceZEN) {
    const totalBalanceFiatNode = document.getElementById("totalBalanceFiat");
    const balanceFiatAmountNode = totalBalanceFiatNode.firstElementChild;
    const LastUpdateTimeNode = document.getElementById("LastUpdateTime");
    let fiat = 'USD' //FIXME: Get from settings the desired fiat currency
    zenToFiat(fiat).then( function(ZENPrice){
      //console.log(ZENPrice);
      const now = new Date();
      // View the output
      console.log(now);
      let balance = (balanceZEN) * ZENPrice;
      //console.log(balance);
      balanceFiatAmountNode.textContent = formatFiatBalance(balance) + " " + fiat;
      LastUpdateTimeNode.textContent = now;

    });
}


function zenToFiat(fiat){
  const fetch = require("node-fetch");
  let BASE_API_URL = 'https://api.coinmarketcap.com/v1//ticker'
  let API_URL = BASE_API_URL + '/zencash/?convert='+ fiat;

  console.log("GET " + API_URL);
  return fetch(API_URL).then( function(resp){
      console.log(`GET ${API_URL} done, status: ${resp.status} ${resp.statusText}`);
      if (!resp.ok)
          throw new Error(`HTTP GET status: ${resp.status} ${resp.statusText}, URL: ${API_URL}`);
      return resp.json()
  }).then( function(responseAsJson) {
    console.log(responseAsJson);
    //console.log(parseFloat(responseAsJson[0].price_usd));
    //console.log(("responseAsJson[0].price_"+fiat.toLowerCase()));
    return parseFloat(eval("responseAsJson[0].price_"+fiat.toLowerCase()));
  });
};

function createAddrItem(addrObj) {
    const addrItem = cloneTemplate("addrItemTemplate");

    addrItem.dataset.addr = addrObj.addr;
    addrItem.dataset.name = addrObj.name || '';
{'fraction_non_alphanumeric': 0.16635353060904964, 'fraction_numerical': 0.0017222483168936903, 'mean_word_length': 4.6104523495827845, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 21, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2523124', 'n_tokens_mistral': 3784, 'n_tokens_neox': 3813, 'n_words': 688}