package platformapi

import (
	"net/http"
	"strings"
	"sync"

	"git.rosy.net.cn/baseapi/utils"
)

type APICookie struct {
	sync.RWMutex
	storeCookies map[string]string
}

func (a *APICookie) createMapIfNeeded() {
	if a.storeCookies == nil {
		a.storeCookies = make(map[string]string)
	}
}

func (a *APICookie) SetCookieWithStr(cookieStr string) {
	cookieList := strings.Split(cookieStr, ";")
	for _, v := range cookieList {
		if index := strings.Index(v, "="); index > 0 {
			pair := []string{
				v[:index],
				v[index+1:],
			}
			// pair[1], _ = url.QueryUnescape(pair[1])
			// if strings.Index(pair[1], "\"") >= 0 {
			// 	pair[1] = url.QueryEscape(strings.Trim(utils.TrimBlankChar(pair[1]), "\""))
			// }
			k := utils.TrimBlankChar(pair[0])
			v := utils.TrimBlankChar(pair[1])
			if k != "" && v != "" {
				a.SetCookie(k, v)
			}
		}
	}
}

func (a *APICookie) SetCookie(key, value string) {
	a.Lock()
	defer a.Unlock()
	a.createMapIfNeeded()
	a.storeCookies[key] = value
}

func (a *APICookie) GetCookie(key string) string {
	a.RLock()
	defer a.RUnlock()
	a.createMapIfNeeded()
	return a.storeCookies[key]
}

func (a *APICookie) GetCookieCount() int {
	a.RLock()
	defer a.RUnlock()
	return len(a.storeCookies)
}

func (a *APICookie) FillRequestCookies(r *http.Request) *http.Request {
	a.RLock()
	defer a.RUnlock()
	for k, v := range a.storeCookies {
		r.AddCookie(&http.Cookie{
			Name:  k,
			Value: v,
		})
	}
	return r
}
