import Dexie, { IndexableType, Table } from 'dexie';
import { decryptCiphertext, encryptPlaintext } from './util';
import { Account, Chains, Excer } from "@/types/appTypes"

export const data_config = { 
    name:'MxM_wallet',
    version:1,
    tables:{
        account:'++id,encryptedPrivateKey,publicKey,address,excer',
        processes:'++id,coin_name,amount,execer,is_main,c_addr,status',
        coin:'++id,name,excer,is_main,c_addr,amount,process_amount'
    }
}

export class DB extends Dexie {
    account: Table<Account, IndexableType>
    processes: Table<Chains, IndexableType>
    constructor() {
        super(data_config.name);
        this.version(data_config.version).stores(data_config.tables);
        this.account = this.table('account');
        this.processes = this.table('processes');
    }


    async getAccountList(): Promise<Account[]> {
        const arr = await this.account.toArray();
        return arr;
    }

    addAccount(key: string, { privateKey, publicKey, address , excer }: { privateKey: string, publicKey: string, address: string, excer: Excer }) {
        return this.account.add({
            encryptedPrivateKey: encryptPlaintext(key, privateKey),
            publicKey,
            address,
            excer
        })
    }

    /**
     * @description 用地址获取账户
     * @param address 
     * @returns 
     */
    async getAccount(address: string): Promise<Account | undefined> {
        const account = await this.account.where('address').equals(address).first();
        return account
    }

    async getPrivateKey(address: string, key: string): Promise<string | undefined> {
        const account = await this.getAccount(address)
        if (account) {
            const encryptedPrivateKey = account.encryptedPrivateKey
            const privateKey = decryptCiphertext(key, encryptedPrivateKey)
            return privateKey;
        }
        return undefined
    }

    deleteAccount(address: string) {
        return this.account.where('address').equals(address).delete()
    }
}
