package proxy

import (
	"encoding/json"
	"regexp"

	"dyproxy/.gen/model"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

func (p *Proxy) processFollowers(body []byte) {
	var follower Follower
	if err := json.Unmarshal(body, &follower); err != nil {
		err = errors.Wrap(err, "unmarshal followers")
		logrus.Error(err)
		return
	}

	followers := []model.Follower{}
	for _, f := range follower.Followers {
		m := model.Follower{
			Avatar:    f.AvatarThumb.URLList[0],
			Nickname:  f.Nickname,
			SecUID:    f.SecUID,
			ShortID:   f.ShortID,
			UID:       f.UID,
			UniqueID:  f.UniqueID,
			ExpertUID: follower.MyselfUserID,
		}

		logrus.Warnf("follower: %+v", m)
		followers = append([]model.Follower{m}, followers...)
	}

	// post followers
	if _, err := p.client.R().SetBody(followers).Post("/api/followers"); err != nil {
		logrus.Error("post /api/followers, ", err)
	}
}

func (p *Proxy) processUserInfo(body []byte) {
	pattern := `self.__pace_f.push\(.*?"uid\\":\\"(.*?)\\",.*?\\"secUid\\":\\"(.*?)\\",.*?\\"shortId\\":\\"(.*?)\\",.*\\"realName\\":\\"(.*?)\\",.*?"nickname\\":\\"(.*?)\\",.*?`
	reg := regexp.MustCompile(pattern)

	matches := reg.FindSubmatch(body)
	if len(matches) == 0 {
		logrus.Error("no match users")
		return
	}

	if len(matches) != 6 {
		logrus.Error("invalid match")
		return
	}

	expert := model.Expert{
		UID:      string(matches[1]),
		SecUID:   string(matches[2]),
		ShortID:  string(matches[3]),
		RealName: string(matches[4]),
		NickName: string(matches[5]),
	}

	logrus.Warnf("expert: %+v", expert)

	// post user info
	if _, err := p.client.R().SetBody(expert).Post("/api/experts"); err != nil {
		logrus.Error("post /api/experts, ", err)
	}
}
