<commit_before>import React from 'react'
import {call, put, select} from 'redux-saga/effects';
import once from 'lodash/once'
import {connect} from 'react-redux'
import transaction from 'app/redux/Transaction'
import LoadingIndicator from 'app/components/elements/LoadingIndicator'
import {PrivateKey} from 'shared/ecc'
import {key_utils} from 'shared/ecc'
import Apis from 'shared/api_client/ApiInstances'
import { translate, translateHtml } from '../../Translator';
import CopyToClipboard from 'react-copy-to-clipboard';
import ClipboardIcon from 'react-clipboard-icon'
import o2j from 'shared/clash/object2json'
import { calculateCurrentStage, currentStage } from '../elements/LandingCountDowns.jsx';
import TimeAgoWrapper from 'app/components/elements/TimeAgoWrapper';
import Tooltip from 'app/components/elements/Tooltip';
//import {test as o2jtest} from 'shared/clash/object2json'

import icoDestinationAddress from 'shared/icoAddress'
/*
	Логика компонента:
	Если пользователь находится на своей странице, и если у него нет Btc адреса, то должна отображаться кнопка генерации адреса.
	Если у пользователя есть BTC адрес, то необходимо отразить аддрес, qr code и табличку с предыдущими транзакциями.
	Если пользователь находится НЕ на своей странице, то отобразить предыдущие транзакции, если они есть.
*/



class BuyGolos extends React.Component {

	state = {
		icoAddress: '',
		transactions: [],
        error: '',
		loading: false,
		checkboxesClicked: [false, false, false],
		checkboxClicked0: false,
		checkboxClicked1: false,
		checkboxClicked2: false,
	}

	handleCheckBoxClick(checkboxNumber, e) {
		// e.preventDefault()
		const checkboxIdentifier = 'checkboxClicked' + checkboxNumber
		const checkbox = this.state[checkboxIdentifier]
		this.setState({ [checkboxIdentifier]: !checkbox })
	}

	generateAddress = event => {
		event && event.preventDefault()

		const {checkboxClicked0, checkboxClicked1, checkboxClicked2} = this.state
		// function isTrue(item) {
		// 	console.log('true', true)
		// 	return item === true
		// }
		if (!(checkboxClicked0, checkboxClicked1, checkboxClicked2)) {
			console.log('error will occure')
			this.setState({
				error: 'Чтобы продолжить, установите этот флажок. Просим Вас внимательно отнестиcь к данной информации во избежание недопонимания.'
			})
			return
		}

		let {metaData, accountname, account} = this.props

		this.setState({ loading: true })

		fetch('/api/v1/generate_ico_address', {
			method: 'post',
			mode: 'no-cors',
			credentials: 'same-origin',
			headers: {
				Accept: 'application/json',
				'Content-type': 'application/json'
			},
			body: JSON.stringify({csrf: $STM_csrf})
		})
		.then(function(data) { return data.json() })
		.then(({icoAddress}) => {
			console.log('icoAddress', icoAddress)
			if (metaData == '{created_at: \'GENESIS\'}') metaData = {created_at: "GENESIS"}
			if (typeof metaData === 'string') metaData = {}
			metaData.ico_address = icoAddress
			metaData = o2j.ifObjectToJSON(metaData);
			this.props.updateMeta({
					json_metadata: metaData,
					account: accountname,
					memo_key: account.memo_key,
					onError: () => this.setState({
						loading: false,
						error: 'server returned error'
					}),
					onSuccess: () => this.setState({
						icoAddress,
						loading: false,
					})
			})
		})
		.catch(error => {
			// TODO dont forget to add error display for user
			this.setState({
				loading: false,
				error: error.reason
			})
			console.error('address generation failed', error)
		})
	}

	removeIco = () => {
		let {metaData} = this.props
		const {accountname, account} = this.props
		console.log('metaData', metaData)
		metaData.ico_address = ''
		metaData = o2j.ifObjectToJSON(metaData);
		this.props.updateMeta({
			account: accountname,
			json_metadata: metaData,
			memo_key: account.memo_key,
			onError: () => this.setState({
				loading: false,
				error: 'server returned error'
			}),
			onSuccess: () => this.setState({
				icoAddress: '',
				loading: false,
			})
		})
	}


	componentDidMount() {
		// if (process.env.BROWSER) this.generateAddress()
		if (process.env.BROWSER) this.fetchTransations()
	}

	fetchTransations = () => {
		const icoAddress = this.state.icoAddress || this.props.icoAddress
		console.log('icoAddress', icoAddress)
		if (!icoAddress) return
		console.log('fetching in progress!')
		fetch(`https://api.blockcypher.com/v1/btc/main/addrs/${icoAddress}`)
		.then(function(data) { return data.json() })
		.then((object) => {
			console.log('object', object)
		})
		.catch(error => {
			// TODO dont forget to add error display for user
			// this.setState({ error: error.reason })
			console.error('transactions fetch failed', error)
		})
	}

	testFormSubmit() {
		console.log(this.icoAddress)
		console.log(this.props)
		console.log("is own: " + this.state.isOwnAccount)

		const k = "foo"
		const v = "bar"
		const p = ""
		const u = "tester"
		let meta = o2j.ifStringParseJSON(this.props.metaData);
    if (typeof meta==='string')
      meta = {created_at: "Genesis"}
		meta[k] = v;
		meta = o2j.ifObjectToJSON(meta);
	}

	render() {
		if (!process.env.BROWSER) { // don't render this page on the server
				return <div className="row">
						<div className="column">
								{translate('loading')}..
						</div>
				</div>;
		}

		const {state, props} = this
		console.log (icoDestinationAddress);
		console.log (state.icoAddress);
		const {
			metaData,
			icoAddress,
			routeParams: {accountname},
		} = props
		const { transactions } = state
		let loading=this.state.loading

		return 	<div id="buy_golos" className="row BuyGolos">

					{/* ACTUAL COMPONENT */}
					{/* <div className="columns small-12">
						<h2>Макет функционала</h2>
						<hr />
					</div> */}
					<button className="button warning" onClick={this.removeIco}>REMOVE ICO ADDRESS</button>
					<div className="columns small-12">
						<h2>ПОКУПКА СИЛЫ ГОЛОСА</h2>
						<hr style={{marginBottom: '50px'}} />
					</div>

					{/* GENERATE ADDRESS */}
					{
						props.isOwnAccount && (!state.icoAddress && !props.icoAddress)<commit_msg> sample data extraction from blockcypher<commit_after>import React from 'react'
import {call, put, select} from 'redux-saga/effects';
import {once, filter, includes} from 'lodash'
import {connect} from 'react-redux'
import transaction from 'app/redux/Transaction'
import LoadingIndicator from 'app/components/elements/LoadingIndicator'
import {PrivateKey} from 'shared/ecc'
import {key_utils} from 'shared/ecc'
import Apis from 'shared/api_client/ApiInstances'
import { translate, translateHtml } from '../../Translator';
import CopyToClipboard from 'react-copy-to-clipboard';
import ClipboardIcon from 'react-clipboard-icon'
import o2j from 'shared/clash/object2json'
import { calculateCurrentStage, currentStage } from '../elements/LandingCountDowns.jsx';
import TimeAgoWrapper from 'app/components/elements/TimeAgoWrapper';
import Tooltip from 'app/components/elements/Tooltip';
//import {test as o2jtest} from 'shared/clash/object2json'

import icoDestinationAddress from 'shared/icoAddress'
/*
	Логика компонента:
	Если пользователь находится на своей странице, и если у него нет Btc адреса, то должна отображаться кнопка генерации адреса.
	Если у пользователя есть BTC адрес, то необходимо отразить аддрес, qr code и табличку с предыдущими транзакциями.
	Если пользователь находится НЕ на своей странице, то отобразить предыдущие транзакции, если они есть.
*/



class BuyGolos extends React.Component {

	state = {
		icoAddress: '',
		transactions: [],
        error: '',
		loading: false,
		checkboxesClicked: [false, false, false],
		checkboxClicked0: false,
		checkboxClicked1: false,
		checkboxClicked2: false,
	}

	handleCheckBoxClick(checkboxNumber, e) {
		// e.preventDefault()
		const checkboxIdentifier = 'checkboxClicked' + checkboxNumber
		const checkbox = this.state[checkboxIdentifier]
		this.setState({ [checkboxIdentifier]: !checkbox })
	}

	generateAddress = event => {
		event && event.preventDefault()

		const {checkboxClicked0, checkboxClicked1, checkboxClicked2} = this.state
		// function isTrue(item) {
		// 	console.log('true', true)
		// 	return item === true
		// }
		if (!(checkboxClicked0, checkboxClicked1, checkboxClicked2)) {
			console.log('error will occure')
			this.setState({
				error: 'Чтобы продолжить, установите этот флажок. Просим Вас внимательно отнестиcь к данной информации во избежание недопонимания.'
			})
			return
		}

		let {metaData, accountname, account} = this.props

		this.setState({ loading: true })

		fetch('/api/v1/generate_ico_address', {
			method: 'post',
			mode: 'no-cors',
			credentials: 'same-origin',
			headers: {
				Accept: 'application/json',
				'Content-type': 'application/json'
			},
			body: JSON.stringify({csrf: $STM_csrf})
		})
		.then(function(data) { return data.json() })
		.then(({icoAddress}) => {
			console.log('icoAddress', icoAddress)
			if (metaData == '{created_at: \'GENESIS\'}') metaData = {created_at: "GENESIS"}
			if (typeof metaData === 'string') metaData = {}
			metaData.ico_address = icoAddress
			metaData = o2j.ifObjectToJSON(metaData);
			this.props.updateMeta({
					json_metadata: metaData,
					account: accountname,
					memo_key: account.memo_key,
					onError: () => this.setState({
						loading: false,
						error: 'server returned error'
					}),
					onSuccess: () => this.setState({
						icoAddress,
						loading: false,
					})
			})
		})
		.catch(error => {
			// TODO dont forget to add error display for user
			this.setState({
				loading: false,
				error: error.reason
			})
			console.error('address generation failed', error)
		})
	}

	removeIco = () => {
		let {metaData} = this.props
		const {accountname, account} = this.props
		console.log('metaData', metaData)
		metaData.ico_address = ''
		metaData = o2j.ifObjectToJSON(metaData);
		this.props.updateMeta({
			account: accountname,
			json_metadata: metaData,
			memo_key: account.memo_key,
			onError: () => this.setState({
				loading: false,
				error: 'server returned error'
			}),
			onSuccess: () => this.setState({
				icoAddress: '',
				loading: false,
			})
		})
	}


	componentDidMount() {
		// if (process.env.BROWSER) this.generateAddress()
		if (process.env.BROWSER) this.fetchTransations()
	}

	fetchTransations = () => {
		const icoAddress = this.state.icoAddress || this.props.icoAddress
		console.log('icoAddress', icoAddress)
		if (!icoAddress) return
		console.log('fetching in progress!')
		fetch(`https://api.blockcypher.com/v1/btc/main/addrs/${icoAddress}/full`)
		.then(function(data) { return data.json() })
		.then((object) => {
			console.log('icoAddressTrans', object)

				// only txs where ico destination appears
			let interestingTxs = filter(object.txs, tx =>
			  tx.addresses.includes(icoDestinationAddress) &&   //tx.inputs.addresses.includes(icoAddress) &&
 				!tx.double_spend);
			console.log("transactions we want to display", interestingTxs);
			interestingTxs.forEach( tx => {
				console.log("tx received at", tx.received)
				console.log("tx confirmed at", tx.confirmed)
				let interestingOutputs = filter(tx.outputs, output => output.addresses.includes(icoDestinationAddress))
				console.log("outputs we re interested in", interestingOutputs)

				//one could use array.map here. i m too old for this.
				let satoshiDestinationReceived = 0
				interestingOutputs.forEach(output => satoshiDestinationReceived+=output.value)
				console.log(` this tx resulted in ${satoshiDestinationReceived} more satoshis raized by crowdsale` );
			})
		})
		.catch(error => {
			// TODO dont forget to add error display for user
			// this.setState({ error: error.reason })
			console.error('transactions fetch failed', error)
		})
		fetch(`https://api.blockcypher.com/v1/btc/main/addrs/${icoDestinationAddress}/balance`)
		.then(function(data) { return data.json() })
		.then((object) => {
			console.log("destination address state", object);
			console.log("current confirmed balance", object.final_balance)
			
		})
		.catch(error => {
			// TODO dont forget to add error display for user
			// this.setState({ error: error.reason })
			console.error('transactions fetch failed', error)
		})
	}

	testFormSubmit() {
		console.log(this.icoAddress)
		console.log(this.props)
		console.log("is own: " + this.state.isOwnAccount)

		const k = "foo"
		const v = "bar"
		const p = ""
		const u = "tester"
		let meta = o2j.ifStringParseJSON(this.props.metaData);
    if (typeof meta==='string')
      meta = {created_at: "Genesis"}
		meta[k] = v;
		meta = o2j.ifObjectToJSON(meta);
	}

	render() {
		if (!process.env.BROWSER) { // don't render this page on the server
				return <div className="row">
						<div className="column">
								{translate('loading')}..
						</div>
				</div>;
		}

		const {state, props} = this
		const {
			metaData,
			icoAddress,
			routeParams: {accountname},
		} = props
		const { transactions } = state
		let loading=this.state.loading

		return 	<div id="buy_golos" className="row BuyGolos">

					{/* ACTUAL COMPONENT */}
					{/* <div className="columns small-12">
						<h2>Макет функционала</h2>
						<hr />
					</div> */}
					<button className="button warning" onClick={this.removeIco}>REMOVE ICO ADDRESS</button>
					<div className="columns small-12">
						<h2>ПОКУПКА СИЛЫ ГОЛОСА</h2>
						<hr style={{marginBottom: '50px'}} />
					</div>

					{/* GENERATE ADDRESS */}
					{
						props.isOwnAccount && (!state.icoAddress && !props.icoAddress)
{'fraction_non_alphanumeric': 0.1365488627102319, 'fraction_numerical': 0.004445432318292954, 'mean_word_length': 3.7595204513399154, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 65, 'https://': 3, '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': '7642021', 'n_tokens_mistral': 5166, 'n_tokens_neox': 4578, 'n_words': 1033}