package analysiscode

import (
	"analysiscode/proto"
	"context"
	"log"
	qu "qfw/util"
	"spiderutil"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

var Client proto.GetCodeClient

func InitCodeGrpcClient() {
	defer qu.Catch()
	log.Println("address:", spiderutil.Config.ServerAddress)
	conn, err := grpc.Dial(spiderutil.Config.ServerAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Println("Init Connect Error: ", err)
	}
	Client = proto.NewGetCodeClient(conn)
}

func GetCodeByPath(path, stype, head, cookie string) (string, string, string) {
	log.Println("path:", path)
	defer qu.Catch()
	getCodeReq := &proto.GetCodebyImgPathReq{
		Imgpath: path,
		Stype:   stype,
		Head:    head,
		Cookie:  cookie,
	}
	resp, err := Client.GetCodeByImgPath(context.Background(), getCodeReq)
	if err != nil {
		log.Println("Get Code Err: ", err)
		return "", "", ""
	}
	log.Println(resp)
	if resp.Code == "" {
		log.Println("Get Result Err: ", err)
	}
	return resp.Code, resp.Head, resp.Cookie
}

// func main() {
// 	InitCodeGrpcClient()
// 	code := GetCodeByPath("https://gdgpo.czt.gd.gov.cn/freecms/verify/verifyCode.do?createTypeFlag=n")
// 	log.Println(code)
// }

// func main_client() {
// 	//conn, err := grpc.Dial("127.0.0.1:8010", grpc.WithInsecure())//grpc.WithInsecure()方法弃用
// 	conn, err := grpc.Dial("127.0.0.1:8010", grpc.WithTransportCredentials(insecure.NewCredentials()))
// 	if err != nil {
// 		log.Fatalf("did not connect: %v", err)
// 	}
// 	defer conn.Close()
// 	client := proto.NewGetCodeClient(conn)
// 	getCodeReq := &proto.GetCodebyImgPathReq{
// 		Imgpath: "http://www.ccgp-tianjin.gov.cn/commons/image.jsp",
// 	}
// 	resp, err := client.GetCodeByImgPath(context.Background(), getCodeReq)
// 	if err != nil {
// 		log.Fatalf("get code err: %v", err)
// 	}
// 	tmp := &ResultInfo{}
// 	json.Unmarshal([]byte(resp.Result), &tmp)
// 	log.Println(resp.Result, resp.String())

// 	log.Println(tmp.Msg, tmp.Info.Code)
// }
