const Transaction = require('./transaction');
const crypto = require('crypto');

class Block {

    constructor(json_or_index, timestamp, transactions, previousHash) {
        if(Number.isInteger(json_or_index)) {
            const index = json_or_index;
            this.index = index;
            this.timestamp = timestamp;
            this.transactions = transactions;
            this.nonce = 0;
            this.previousHash = previousHash;
        }else{
            const json = json_or_index;
            this.index = json.index;
            this.timestamp = json.timestamp;
            this.transactions = json.transactions;
            this.nonce = json.nonce;
            this.previousHash = json.previousHash;
        }
    }

    object() {
        return {
            index: this.index,
            timestamp: this.timestamp,
            transactions: this.transactions,
            nonce: this.nonce,
            previousHash: this.previousHash
        }
    }

    hash() {
        const json = JSON.stringify(this.object());
        return crypto.createHash('sha256').update(json, 'utf8').digest('hex');
    }

    isValidBlock(previousBlock) {
        return previousBlock.hash() == this.previousHash 
        && this.index == previousBlock.index + 1
        && this.timestamp > previousBlock.timestamp
        && this.transactions != undefined
        && this.nonce != undefined
    }
}

module.exports = Block;