package main

import "github.com/hyperledger/fabric/core/chaincode/shim"
import (
	pb "github.com/hyperledger/fabric/protos/peer"
	"fmt"
	"encoding/json"
	"strings"
)

const KEY  = "COUPONS-"
type CPSChainCode struct {
}

func (t *CPSChainCode) Init(stub shim.ChaincodeStubInterface) pb.Response {
	return shim.Success([]byte("init successful! "))
}
func (t *CPSChainCode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
	functionName, args := stub.GetFunctionAndParameters()
	paths := splitPath(functionName)
	return Router(paths, args, stub)
}

func Router(paths, args []string, stub shim.ChaincodeStubInterface) pb.Response {
	switch paths[0] {
	case "certManagement": //证书管理
		return certManagement(paths,args, stub)
	case "getCoupons": //机构查询发行的券信息
		return getCouponsApi(args, stub)
	case "getCouponsByAddress": //通过UTXO地址查看资产信息
		return getCouponsByAddressApi(args, stub)
	case "subsidies": //补贴请求
		return subsidiesApi(args, stub)
	case "createTx":
		return transactionProcess(paths,args, stub)
	default:
		return shim.Error(fmt.Sprintf("Unsupported function %s", paths[0]))
	}
}
//入参：券id、机构证书、机构签名
func getCouponsApi(args []string, stub shim.ChaincodeStubInterface) pb.Response {
	// 解析请求数据
	trans,_,_,err := messageToTrans(CreateCoupon,args,stub)
	if err != nil{
		return shim.Error(err.Error())
	}
	var coupon Coupons
	expand, ok := trans.Value.(string) //判断类型
	if !ok {
		return shim.Error("Error expanding parameter type，must be string")
	}
	err = json.Unmarshal([]byte(expand), &coupon)
	if err != nil {
		return shim.Error("Parameter resolution failed" + err.Error())
	}
	coupByte,err :=getStateByte(KEY+coupon.CoupId,stub)
	if err != nil{
		return shim.Error(err.Error())
	}
	return shim.Success(coupByte)
}

// 入参：utxo地址，证书、交易签名.商家查看，只能查看已领取的UTXO
func getCouponsByAddressApi(args []string, stub shim.ChaincodeStubInterface) pb.Response {
	// 解析请求数据
	trans,_,_,err := messageToTrans(UseCoupon,args,stub)
	if err != nil{
		return shim.Error(err.Error())
	}
	//查询utxo信息
	utxo,err :=getStateUtxo(KEY+trans.From,stub)
	if err != nil{
		return shim.Error(err.Error())
	}
	if strings.Compare(utxo.Status,"3") != 0{
		return shim.Error("Query for exceptions, UTXO status exceptions")
	}
	utxoByte,_ :=json.Marshal(utxo)
	return shim.Success(utxoByte)
}


// 入参：商户公钥、机构证书、交易签名
//出参：交易流水
func subsidiesApi(args []string, stub shim.ChaincodeStubInterface) pb.Response {
	// 解析请求数据
	trans,_, _,err := messageToTrans(CreateCoupon,args,stub)
	// 根据商户公钥查询出该商户所有UTXO记录
	arg :="{\"selector\":{\"public_key\":\""+trans.ToPub+"\"}}"
	transferInfo,err :=getStateByConditions(arg,stub)
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success(transferInfo)
}


func main() {
	err := shim.Start(&CPSChainCode{})
	if err != nil {
		fmt.Printf("Error starting EncCC chaincode: %s", err)
	}
}