package client

import (
	"io/ioutil"
	"k8s.io/apimachinery/pkg/util/json"
	"log"
	"net/http"
	"strings"
	"sync"
)

type task struct {
	sync.RWMutex
	client  *client
	options *TaskOptions
	log     log.Logger
}

func newTask(client *client, options *TaskOptions) (*task, error) {
	task := &task{
		RWMutex: sync.RWMutex{},
		client:  client,
		options: options,
		log:     log.Logger{},
	}
	return task, nil
}

func (t *task) PullTaskInfo(pullTaskInfoReq PullTaskInfoReq) (*PullTaskInfoResp, error) {

	url := t.client.url + "/pcm/v1/core/pullTaskInfo"
	method := "GET"
	infoReq := PullTaskInfoReq{AdapterId: pullTaskInfoReq.AdapterId}
	jsonStr, _ := json.Marshal(infoReq)
	payload := strings.NewReader(string(jsonStr))

	client := &http.Client{}
	req, _ := http.NewRequest(method, url, payload)
	req.Header.Add("Content-Type", "application/json")
	res, _ := client.Do(req)
	defer res.Body.Close()

	body, _ := ioutil.ReadAll(res.Body)
	var resp PullTaskInfoResp
	json.Unmarshal(body, &resp)
	return &resp, nil
}

func (t *task) PushTaskInfo(pushTaskInfoReq PushTaskInfoReq) (*PushTaskInfoResp, error) {

	url := t.client.url + "/pcm/v1/core/pushTaskInfo"
	method := "POST"
	//infoReq := PullTaskInfoReq{AdapterId: pushTaskInfoReq.AdapterId}
	jsonStr, _ := json.Marshal(pushTaskInfoReq)
	payload := strings.NewReader(string(jsonStr))

	client := &http.Client{}
	req, _ := http.NewRequest(method, url, payload)
	req.Header.Add("Content-Type", "application/json")
	res, _ := client.Do(req)
	defer res.Body.Close()

	body, _ := ioutil.ReadAll(res.Body)
	var resp PushTaskInfoResp
	json.Unmarshal(body, &resp)
	return &resp, nil
}

func (t *task) PushResourceInfo(pushResourceInfoReq PushResourceInfoReq) (*PushResourceInfoResp, error) {

	url := t.client.url + "/pcm/v1/core/pushResourceInfo"
	method := "POST"
	//infoReq := PushResourceInfoReq{AdapterId: pushResourceInfoReq.AdapterId}
	jsonStr, _ := json.Marshal(pushResourceInfoReq)
	payload := strings.NewReader(string(jsonStr))

	client := &http.Client{}
	req, _ := http.NewRequest(method, url, payload)
	req.Header.Add("Content-Type", "application/json")
	res, _ := client.Do(req)
	defer res.Body.Close()

	body, _ := ioutil.ReadAll(res.Body)
	var resp PushResourceInfoResp
	json.Unmarshal(body, &resp)
	return &resp, nil
}
