package net.sergeych

import com.icodici.universa.HashId
import com.icodici.universa.contract.TransactionPack
import kotlinx.coroutines.runBlocking
import net.sergeych.uni.Uni
import java.io.File

fun main(_args: Array<String>) {
    val args = _args.toMutableList()

    println("\nINDIGO sample console tool\n")
//    val args = mutableListOf("-c", "???")
    runBlocking {
        println("Connecting to Universa network...")

        // connect to the network and print out nodes info
        Uni.versa {
            println("Connected. Here is the list of nodes:")
            topologyInfo.forEach {
                println("${it.ipUrl} or ${it.domainUrl}: ${it.keyAddress}")
            }
        }
        while (args.isNotEmpty()) {
            if (args[0] == "-h") {
                println("\nUsage:")
                println("  -c <contractID | contractFile> - check contract approval")
                println("  -h - this help")
                break
            }
            processCheckContract(args)
        }
        // universa client runs background coroutines here, so we shall cancel them
        System.exit(0)
    }
}

/**
 * if args start with "-c", checks the contractId or loads the contract using args[1]
 * and checks network approval, and remove both arguments from args array.
 */
suspend fun processCheckContract(args: MutableList<String>) {
    if (args[0] == "-c") {
        val contractId = if (args[1].endsWith(".unicon")) {
            // got a file, load it using TransactionPack format (common for contracts):
            val c = TransactionPack.unpack(
                File(args[1]).readBytes()
            )
                // and extract its main contract:
                .contract

            println("\nLoaded contract: ${c.id.toBase64String()}")
            println("Definition ---------------------------------------------- ")
            println("Created   : ${c.definition.createdAt}")
            println("Expires   : ${c.definition.expiresAt}")
            println("Ext.type  : ${c.definition.extendedType}")
            println("Definition: ${c.definition.data}")
            println("State --------------------------------------------------- ")
            println("Revision : ${c.state.revision}")
            println("Branch   : ${c.state.branchId}/${c.state.branchRevision}")
            println("State data    : ${c.state.data}")

            if( c.transactional != null ) {
                println("Transactional -------------------------------------------")
                println("data: ${c.transactional!!.data}")
            }

            // return its id for further checks:
            c.id
        } else
            HashId.withDigest(args[1])

        // -c <contract-id | contract-file>
        // remove arguments
        args.removeAt(0)
        args.removeAt(0)

        // check contract approval from the universa network:
        print("\nChecking contract Id: $contractId: ")

        val isApproved = Uni.versa { isApprovedByNetwork(contractId) }

        println(if (isApproved) "Approved" else "Rejected")
    }
}
