var Web3 = require('web3');
var web3 = new Web3();
import { signPersonalMessage, signMessage } from '@/api/demoMETAMASK';


export function getKey(chainId, address){
  return `${chainId}-${address}`;
}


export async function sign(chainId, addres, expireTime){
    const  str = `${chainId}-${addres}-${expireTime}`;
    const signature = await signPersonalMessage(str);
    return signature;
}

export async function setSignatureInfo(chainId, address){
    let expireTime = parseInt(Date.now()/1000) + 24 * 60 *  60;
    const signature = await sign(chainId, address, expireTime)
    try{
        const signatures = localStorage.getItem('_IS') ? JSON.parse(localStorage.getItem('_IS')) : {};
        const key = getKey(chainId, address);
        let info = {
            signature,
            expireTime,
        }
        signatures[key] = info;
        localStorage.setItem('_IS', JSON.stringify(signatures));
        return info;
    }catch(err){
        console.log('--err', err)
    }
}

export function getSignatureInfo(chainId, address){
    try{
        const signatures = JSON.parse(localStorage.getItem('_IS')|| '') || {};
        let key = getKey(chainId, address);
        const content = signatures[key] || {};
        return {
            signature: content.signature,
            expireTime: content.expireTime,
        };
    }catch(err){

    }
    return {};
}


export function signatureHasExpired(chainId, address){
     let {expireTime} = getSignatureInfo(chainId, address);
     let now = parseInt(Date.now()/1000);
     return !expireTime || now >= expireTime;
}

export function delSignatureInfo(chainId, address){
    try{
        const signatures =  JSON.parse(localStorage.getItem('_IS'));
        const key = getKey(chainId, address);
        signatures[key] = {};
        localStorage.setItem('_IS', JSON.stringify(signatures));
    }catch(err){
        console.log('--err', err)
    }
}


