package zcash

import (
	"encoding/json"
	//"errors"
	"fmt"
	"strconv"
	. "template"
	"time"

	simplejson "github.com/go-simplejson"
	tml "github.com/toml-master"
)

var (
	BucketZEC string = "ZEC"
	ZecConfig config
	zcashOp   ZcashApi
)

type Zcash struct{}

const (
	NameZcash = "ZEC"
)

func (m Zcash) InitDriver(parm interface{}) bool {
	if m.initconfig() == false {
		return false
	}
	go m.zcashgetinfo()
	return true
}

//get the server's total available balance
func (m Zcash) CoinBalance(parm interface{}) ([]byte, error) {

	confirmedBalance, err := zcashOp.WalleGetBalance("")
	if err != nil {
		LOG("ERROR", "zcash GetBalance err:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETBALANCE_ERR, getErrMsg(GETBALANCE_ERR, nil))
	}

	UnconfirmedBalance, err := zcashOp.WalleGetUnconfirmedBalance("")
	if err != nil {
		LOG("ERROR", "zcash GetUnconfirmedBalance err:%s", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETUNCONFIRMEDBALANCE_ERR, getErrMsg(GETUNCONFIRMEDBALANCE_ERR, nil))
	}

	var jbuf []byte
	resp := make(map[string]interface{})
	resp["confirmedbalance"] = confirmedBalance
	resp["unconfirmed"] = UnconfirmedBalance
	resp["errcode"] = 0
	resp["exact"] = 0

	if jbuf, err = json.Marshal(resp); err != nil {
		LOG("ERROR", "zcash inner json error:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
	}

	return jbuf, nil
}

//Returns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.
func (m Zcash) TransInfo(parm interface{}) ([]byte, error) {

	pjs := parm.(*simplejson.Json)
	startH := pjs.Get("starth").MustUint64()
	endH := pjs.Get("endh").MustUint64()

	if startH < 1 {
		startH=1
	}

	//get longest block count
	blockcount, err := zcashOp.WalleGetBlockCount()
	if err != nil {
		LOG("ERROR", "zcash WalleGetBlockCount  err:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETCLOCKCOUNT_ERR, getErrMsg(GETCLOCKCOUNT_ERR, nil))
	}
	
	//first get block hash and time by height

	if startH > blockcount {
		LOG("DEBUG", "zcash startheight:%v >  blockcount:%v", startH, blockcount)
		startH = blockcount
	}

	startheight := strconv.FormatUint(uint64(startH-1), 10)
	startblockhash, _, err := zcashOp.WalletGetBlockinfo(startheight)
	if err != nil {
		LOG("ERROR", "zcash GetBlockinfo startH:%v err:%v", startH, err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETBLOCKINFO_ERR, getErrMsg(GETBLOCKINFO_ERR, nil))
	}
	
	if endH > blockcount {
		LOG("DEBUG", "zcash endheight:%v >  blockcount:%v", endH, blockcount)
		endH = blockcount
	}

	endheight := strconv.FormatUint(endH, 10)
	_, endblocktime, err := zcashOp.WalletGetBlockinfo(endheight)
	if err != nil {
		LOG("ERROR", "zcash GetBlockinfo endH:%v err:%v", endH, err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETBLOCKINFO_ERR, getErrMsg(GETBLOCKINFO_ERR, nil))
	}

	//Get all transactions in blocks since block [blockhash]
	resp, err := zcashOp.WalleListSinceBlock(startblockhash)
	if err != nil {
		LOG("ERROR", "zcash WalleListSinceBlock err:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, TRANSINFO_ERR, getErrMsg(TRANSINFO_ERR, nil))
	}

	var zcashlisttransactionsinfo []Zcashlisttransactions

	if err = json.Unmarshal([]byte(resp), &zcashlisttransactionsinfo); err != nil {
		LOG("ERROR", "zcash inner json error:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
	}

	outputsArr := make([]map[string]interface{}, 0)

	for _, zcashtransaction := range zcashlisttransactionsinfo {

		// get all transactions from block startHright to endHeight
		if zcashtransaction.Blocktime <= endblocktime {
			requestData := make(map[string]interface{})
			height, err :=zcashOp.WalletGetBlockHeight(zcashtransaction.Blockhash)
			if err != nil {
				LOG("ERROR", "zcash WalletGetBlockHeight error:%v", err.Error())
				return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETBLOCKINFO_ERR, getErrMsg(GETBLOCKINFO_ERR, nil))
			}
			requestData["confirmationheight"] =height
			requestData["address"] = zcashtransaction.Address
			requestData["confirmationtimestamp"] = zcashtransaction.Timereceived
			requestData["value"] = zcashtransaction.Amount
			requestData["transactionid"] = zcashtransaction.Txid
			requestData["confirmations"] = zcashtransaction.Confirmations
			requestData["walletaddress"] = true

			outputsArr = append(outputsArr, requestData)
		}
	}

	var jbuf []byte
	resptmp := make(map[string]interface{})
	resptmp["errcode"] = 0
	resptmp["cointype"] = "ZEC"
	resptmp["outputs"] = outputsArr

	if jbuf, err = json.Marshal(resptmp); err != nil {
		LOG("ERROR", "zcash inner json error:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
	}
	return jbuf, nil

}

//Sent an amount from an account to a zcash address.
func (m Zcash) TransferAccounts(parm interface{}) ([]byte, error) {

	pjs := parm.(*simplejson.Json)
	amountTmp := pjs.Get("amount").MustString()
	destination := pjs.Get("address").MustString()

	if len(amountTmp) == 0 {
		LOG("ERROR", "zcash amount illeagal")
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, AMOUNT_ERR, getErrMsg(AMOUNT_ERR, nil))
	}
	f, err := strconv.ParseFloat(amountTmp, 64)
	if err != nil {
		LOG("ERROR", "zcash inner json error:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
	}

	amount := float64(f)

	transactionid, err := zcashOp.WalleSendFrom("", destination, amount, 1, "", "")
	if err != nil {
		LOG("ERROR", "zcash Send coin error:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, SENDCOINS_ERR, getErrMsg(SENDCOINS_ERR, nil))
	}

	if len(transactionid) != 0 {
		var jbuf []byte
		resp := make(map[string]interface{})
		resp["transactionid"] =[] string{transactionid}
		resp["errcode"] = 0
		resp["msg"] = "ok"

		if jbuf, err = json.Marshal(resp); err != nil {
			LOG("ERROR", "zcash inner json error:%v", err.Error())
			return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
		}
		return jbuf, nil
	}
	LOG("ERROR", "zcash transactionid is null error:%v", err.Error())
	return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
}

//create a new Zcash t-address&key for receiving payments
func (m Zcash) CreateAddress(parm interface{}) ([]byte, error) {

	addr, err := zcashOp.WalletNewAddr()
	if err != nil {
		LOG("ERROR", "zcash  get new t-address error:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETNEWADDRESS_ERR, getErrMsg(GETNEWADDRESS_ERR, nil))
	}
	if len(addr) != 0 {
		//get key by the address
		key, err := zcashOp.WalletDumpPrivKey(addr)

		if err != nil {
			LOG("ERROR", "zcash dump private key error:%v", err.Error())
			return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, DUMPPRIVKEY_ERR, getErrMsg(DUMPPRIVKEY_ERR, nil))
		}
		if len(key) != 0 {

			var jbuf []byte
			resp := make(map[string]interface{})
			resp["address"] = addr
			resp["privkey"] = key
			resp["errcode"] = 0

			if jbuf, err = json.Marshal(resp); err != nil {
				LOG("ERROR", "zcash inner json error:%v", err.Error())
				return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
			}
			return jbuf, nil
		}
		LOG("ERROR", "zcash privkey is null error:%v")
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
	}
	LOG("ERROR", "zcash address is null error:%v")
	return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
}

func (m Zcash) zcashgetinfo() bool {
	fmt.Println("zcashgetinfo begin:")
	for {
		time.Sleep(time.Second)
	}
}

//config rpc from zcash.toml
func (m Zcash) initconfig() bool {
	if _, err := tml.DecodeFile("./src/zcash/zcash.toml", &ZecConfig); err != nil {
		fmt.Println(err)
		return false
	}

	fmt.Printf("%+v\n", ZecConfig)

	zcashUser := ZecConfig.ZcashRpc.Zcashrpcuser
	zcashPassword := ZecConfig.ZcashRpc.Zcashrpcpassword
	zcashHost := ZecConfig.ZcashRpc.Zcashhost
	zcashPort := ZecConfig.ZcashRpc.Zcashport

	zcashOp.InitRpcConf(zcashUser, zcashPassword, zcashHost, zcashPort)
	
	initZcashErr()

	f, err := strconv.ParseFloat(ZecConfig.Limit.Fee, 64)
	if err != nil {
		LOG("ERROR", "zcash inner json error:%v", err.Error())
		return false
	}

	fee := float64(f)
	zcashOp.WalletSetTxFee(fee)
	return true
}

func (m Zcash) ChainHeight(parm interface{}) ([]byte, error) {

	blockcount, err := zcashOp.WalleGetBlockCount()
	if err != nil {
		LOG("ERROR", "zcash  get current block count error:%v", err.Error())
		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETCLOCKCOUNT_ERR, getErrMsg(GETCLOCKCOUNT_ERR, nil))
	}

	sendstr := fmt.Sprintf(`{"errcode":%v,"height":%v}`, OK, blockcount)
	return []byte(sendstr), nil
}
func (m Zcash) ListUnspent(parm interface{}) ([]byte, error) {
	return nil, nil
}
func (m Zcash) SendRawTransaction(parm interface{}) ([]byte, error) {
        return nil, nil
}


func init() {
	Register(NameZcash, &Zcash{})
}
