package main

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

func splitPath(key string) []string {
	key = strings.Trim(key, "/ ")
	if key == "" {
		return []string{}
	}
	return strings.Split(key, "/")
}

//解析前端数据   证书验证  和 签名验证  撒大声地所多所多多所多所多
func messageToTrans(operation TxType,args []string,stub shim.ChaincodeStubInterface) (*Trans,*Message,  string ,error) {
	if len(args) != 3 {
		return nil,nil, "",fmt.Errorf("put data operation expected more than 3 parameters! ")
	}
	message := &Message{
		OwnId: args[0],
		Data: args[1],
		Sign: args[2],
	}
	if message.OwnId == "" || message.Sign == "" || message.Data == "" {
		return nil,nil,"" ,fmt.Errorf("Parameter exception, cannot be null!")
	}
	//验证证书和签名
	pubKey ,err := CheckCertSignature(message,operation,stub)
	if err != nil{
		 return nil,nil,"",err
	}
	fmt.Println("1",message.Data)
	var trans Trans
	err = json.Unmarshal([]byte(message.Data), &trans)
	if err != nil {
		return nil,nil,"", fmt.Errorf("参数解析失败"+err.Error())
	}
	return &trans,message,pubKey , nil
}

func parseArgsToOrderInfo(dat map[string]interface{}) (string,string,SignatureAlgorithm,error) {
	//拿到订单信息
	order, ok := dat["order"].(string)
	if !ok {
		return "","",-1,fmt.Errorf("Error order parameter type，must be string")
	}
	//订单签名信息
	orderSign, ok := dat["orderSign"].(string)
	if !ok {
		return "","",-1,fmt.Errorf("Error orderSign parameter type，must be string")
	}
	//拿到订单信息
	algorithm, ok := dat["algorithm"].(float64)
	if !ok {
		return "","",-1,fmt.Errorf("Error algorithm parameter type，must be int")
	}
	var algo SignatureAlgorithm
	switch algorithm {
	case 1:
		algo = SM2WithSM3
	case 2:
		algo = ECDSAWithSHA256
	}
	return order,orderSign,algo,nil
}

func hexStringToBytes(s string) []byte {
	bs := make([]byte, 0)
	for i := 0; i < len(s); i = i + 2 {
		b, _ := strconv.ParseInt(s[i:i+2], 16, 16)
		bs = append(bs, byte(b))
	}
	return bs
}