package main

import (
	"errors"
	"fmt"
	"template"
	"time"
	_ "zcash"
	_ "lite"
	_ "bucash"
	_ "bitcoin"
)

func coinStart() {

	go dataProcesser(CPUNUM)
	httpNetWorkServer()
}

type taskHandler struct {
	retcode  int
	data     []byte
	complete chan bool
}

func NewtaskHandler() *taskHandler {

	taskhdl := &taskHandler{}
	taskhdl.complete = make(chan bool, 1)
	return taskhdl
}

func (s *taskHandler) waitProcessData() ([]byte, error) {

	timeout := time.NewTicker(time.Duration(200) * time.Second)
	select {
	case <-timeout.C:
		log.Error("deal request timeout")
		return nil, errors.New("timeout")
	case <-s.complete:
	}

	//	if s.retcode != 0 {
	//		//sendstr := fmt.Sprintf(`{"errocde":%v,"msg":"%v"}`, s.retcode, GetErrMsg(s.retcode, s.data))
	//		//return []byte(sendstr), nil
	//		return s.data
	//	}
	return s.data, nil

}

func dataProcesser(processNum int) {
	for i := 0; i < processNum; i++ {
		go func(index int) {
			for {
				task := <-taskChan[index]
				go processer(task)
			}
		}(i)

	}

}

func processer(task *taskInfo) {
	c, err := template.New(task.cointype)
	if err != nil {
		//task.resp.retcode = UNKNOWN_ERR
		sendstr := fmt.Sprintf(`{"errcode:%v,"msg":"%v"}`, INIT_DRIVER_ERR, GetErrMsg(INIT_DRIVER_ERR, nil))
		log.Error("sendstr:%v", sendstr)
		task.resp.data = []byte(sendstr)
		task.resp.complete <- false
		return
	}
	log.Debug("urlpath:%v", task.urlpath)
	resp, err := template.Handler[task.urlpath](c, task.jshandler)
	if err != nil {
		//task.resp.retcode = UNKNOWN_ERR
		task.resp.data = []byte(err.Error())
		task.resp.complete <- false
		return
	}

	task.resp.retcode = OK
	task.resp.data = resp
	task.resp.complete <- true

	return

}
