import React, {useState, useEffect} from 'react';
import {Grid, Typography, Paper, Button, Divider, TextField} from '@material-ui/core';
import {Link} from 'react-router-dom';
import { useAlert } from "react-alert";
import { useTheme } from '@material-ui/core/styles';
import detectEthereumProvider from '@metamask/detect-provider';
const Settings = (props) => {
const { globalUrl, isLoaded, userdata, setUserData } = props;
const theme = useTheme();
const alert = useAlert()
const [username, setUsername] = useState("");
const [firstname, setFirstname] = useState("");
const [lastname, setLastname] = useState("");
const [title, setTitle] = useState("");
const [companyname, setCompanyname] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [newPassword2, setNewPassword2] = useState("");
const [file, setFile] = React.useState("")
const [fileBase64, setFileBase64] = React.useState(userdata.image === undefined || userdata.image === null ? theme.palette.defaultImage : userdata.image)
const [loadedValidationWorkflows, setLoadedValidationWorkflows] = React.useState([])
const [selfOwnedWorkflows, setSelfOwnedWorkflows] = React.useState([])
const [loadedWorkflowCollections, setLoadedWorkflowCollections] = React.useState([])
// Used for error messages etc
const [formMessage, ] = useState("");
const [passwordFormMessage, setPasswordFormMessage] = useState("");
const [firstrequest, setFirstRequest] = useState(true)
const [userSettings, setUserSettings] = useState({})
/*
const [userdata.eth_info, setEthInfo] = useState(userdata.eth_info !== undefined && userdata.eth_info.account !== undefined && userdata.eth_info.account.length > 0 ? userdata.eth_info : {
"account": "",
"balance": "",
})
*/
/*
console.log(userdata.eth_info)
if (userdata.eth_info.account.length === 0 && userdata.eth_info !== undefined && userdata.eth_info.account !== undefined && userdata.eth_info.account.length > 0) {
setEthInfo(userdata.eth_info)
} else if (userdata.eth_info.balance.length > 0 && userdata.eth_info.parsed_balance === undefined) {
//console.log(window.ethereum)
//console.log(window.ethereum.utils.formatEther(userdata.eth_info.balance))
const parsed_balance = parseInt(userdata.eth_info.balance, 16)/1000000000000000000
console.log("Parsed balance: ", parsed_balance)
userdata.eth_info.parsed_balance = parsed_balance
userdata.eth_info.parsed_balance = parsed_balance
setEthInfo(userdata.eth_info)
} else if (userdata.eth_info !== undefined && userdata.eth_info.balance !== userdata.eth_info.balance) {
console.log("Updating balance: ", userdata.eth_info)
setEthInfo(userdata.eth_info)
}
*/
//Returns the value from a storage position at a given address.
const isCloud = window.location.host === "localhost:3002" || window.location.host === "shuffler.io"
const bodyDivStyle = {
margin: "auto",
textAlign: "center",
width: "1100px",
}
const boxStyle = {
flex: "1",
color: "white",
position: "relative",
marginLeft: "10px",
marginRight: "10px",
paddingLeft: "30px",
paddingRight: "30px",
paddingBottom: "30px",
paddingTop: "30px",
backgroundColor: theme.palette.surfaceColor,
display: "flex",
flexDirection: "column"
}
const checkOwner = (data, userdata) => {
var currentOwner = false
if (data.owner.address === userdata.eth_info.account) {
currentOwner = true
} else {
if (data.top_ownerships !== undefined && data.top_ownerships !== null && data.top_ownerships.length === 1) {
for (var key in data.top_ownerships) {
if (data.top_ownerships[key].owner.address === userdata.eth_info.account) {
currentOwner = true
break
}
}
}
}
return currentOwner
}
const onPasswordChange = () => {
const data = {"username": userSettings.username, "currentpassword": currentPassword, "newpassword": newPassword, "newpassword2": newPassword2}
const url = globalUrl+'/api/v1/passwordchange';
fetch(url, {
mode: 'cors',
method: 'POST',
body: JSON.stringify(data),
credentials: 'include',
crossDomain: true,
withCredentials: true,
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
})
.then(response =>
response.json().then(responseJson => {
if (responseJson["success"] === false) {
setPasswordFormMessage(responseJson["reason"])
} else {
alert.success("Changed password!")
setPasswordFormMessage("")
}
}),
)
.catch(error => {
setPasswordFormMessage("Something went wrong.")
});
}
const loadWorkflowOwnership = () => {
fetch(globalUrl+"/api/v1/workflows/collections/untitled-collection-103712081", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: "include",
})
.then((response) => {
if (response.status !== 200) {
console.log("Status not 200 for WORKFLOW EXECUTION :O!")
}
return response.json()
})
.then((responseJson) => {
//console.log("Values: ", responseJson)
// const [selfOwnedWorkflows, setSelfOwnedWorkflows] = React.useState([])
if (responseJson !== undefined && responseJson !== null) {
const filteredOwnerships = responseJson.filter(data => checkOwner(data, userdata) === true)
if (filteredOwnerships !== undefined && filteredOwnerships !== null && filteredOwnerships.length > 0) {
setSelfOwnedWorkflows(filteredOwnerships)
}
var collections = []
for (var key in responseJson) {
var collectionname = responseJson[key].collection.name
if (!collections.includes(collectionname)) {
collections.push(collectionname)
}
}
console.log(collections)
setLoadedWorkflowCollections(collections)
setLoadedValidationWorkflows(responseJson)
setTimeout(() => {
window.scrollTo({
top: document.body.scrollHeight,
left: 0,
behavior: 'smooth'
})
}, 250)
}
})
.catch(error => {
console.log(error)
})
}
const generateApikey = () => {
fetch(globalUrl+"/api/v1/generateapikey", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: "include",
})
.then((response) => {
if (response.status !== 200) {
console.log("Status not 200 for WORKFLOW EXECUTION :O!")
}
return response.json()
})
.then((responseJson) => {
setUserSettings(responseJson)
})
.catch(error => {
console.log(error)
});
}
const getSettings = () => {
fetch(globalUrl+"/api/v1/getsettings", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: "include",
})
.then((response) => {
if (response.status !== 200) {
console.log("Status not 200 for WORKFLOW EXECUTION :O!")
}
return response.json()
})
.then((responseJson) => {
setUserSettings(responseJson)
})
.catch(error => {
console.log(error)
});
}
// Gotta be a better way of doing this rofl
const setFields = () => {
if (userdata.username !== undefined) {
if (userdata.username.length > 0) {
setUsername(userdata.username)
}
//if (userdata.firstname.length > 0) {
// setFirstname(userdata.firstname)
//}
//if (userdata.lastname.length > 0) {
// setLastname(userdata.lastname)
//}
//if (userdata.title.length > 0) {
// setTitle(userdata.title)
//}
//if (userdata.companyname.length > 0) {
// setCompanyname(userdata.companyname)
//}
//if (userdata.phone.length > 0) {
// setPhone(userdata.phone)
//}
//if (userdata.email.length > 0) {
// setEmail(userdata.email)
//}
}
}
const registerProviders = (userdata) => {
// Register hooks here
detectEthereumProvider()
.then((provider) => {
if (provider) {
if (!provider.isMetaMask) {
alert.error("Only MetaMask is supported as of now.")
return
}
// Find the ethereum network
// Get the users' account(s)
//alert.info("Connecting to MetaMask")
//console.log("Connected: ", provider.isConnected())
if (!provider.isConnected()) {
alert.error("Metamask is not connected.")
return
}
provider.on('message', (event) => {
alert.info("Ethereum message: ", event)
})
provider.on('chainChanged', (chainId) => {
console.log("Changed chain to: ", chainId)
const method = "eth_getBalance"
const params = [
userdata.eth_info.account,
"latest"
]
provider.request({
method: method,
params,
})
.then((result) => {
console.log("Got result: ", result)
if (result !== undefined && result !== null) {
userdata.eth_info.balance = result
userdata.eth_info.parsed_balance = result/1000000000000000000
console.log("INFO: ", userdata)
setUserData(userdata)
} else {
alert.error("Couldn't find balance: ", result)
}
})
.catch((error) => {
// If the request fails, the Promise will reject with an error.
alert.error("Failed getting info from ethereum API: "+error)
})
})
}
})
}
// This should "always" have data
useEffect(() => {
if (firstrequest) {
setFirstRequest(false)
getSettings()
//registerProviders(userdata)
}
if (Object.getOwnPropertyNames(userdata).length > 0 && (username === "" && email === "")) {
setFields()
}
})
const ParsedWorkflowView = (props) => {
const { data } = props;
var innerPaperStyle = {
backgroundColor: theme.palette.inputColor,
display: "flex",
flexDirection: "column",
padding: "0px 0px 12px 0px",
borderRadius: theme.palette.borderRadius,
}
const currentOwner = checkOwner(data, userdata)
if (currentOwner === true) {
innerPaperStyle.border = "3px solid #f86a3e"
}
return (
const landingpageData =