package main

import (
	"fmt"
	"log/slog"
	"sync"
)

type Work struct {
	Lock sync.Mutex

	Task map[string]chan<- interface{}
	// userClient map[string]*Client
}

var Worker Work

func init() {
	Worker = Work{
		Task: make(map[string]chan<- interface{}),
		//userClient: make(map[string]*Client),
	}
}

func (w *Work) StopJob(userId, taskType string) error {
	w.Lock.Lock()

	if v, ok := w.Task[userId+"-"+taskType]; ok {
		close(v)
		delete(w.Task, userId+"-"+taskType)

	} else {
		return fmt.Errorf("%s do not run", userId+"-"+taskType)
	}

	// done := w.RunJob(t)
	// w.Task[t.UserId+"-"+t.TaskType] = done
	w.Lock.Unlock()

	return nil
}

func (w *Work) AddJob(t TaskJob) error {
	w.Lock.Lock()

	if _, ok := w.Task[t.UserId+"-"+t.TaskType]; ok {
		return fmt.Errorf("%s has run", t.UserId+"-"+t.TaskId+"-"+t.TaskType)
	}

	done := w.RunJob(t)

	w.Task[t.UserId+"-"+t.TaskType] = done

	w.Lock.Unlock()

	return nil
}

func (w *Work) RunJob(t TaskJob) chan<- interface{} {

	done := make(chan interface{})
	go func() {
		var cli *Client

		if t.TaskType == RetweetType {
			cli = NewRetweeterClient(t.Config)
		} else {
			cli = NewLikeClient(t.Config)
		}

		page := NewPageUsers(NewIdx(t.Idx))

		for {

			select {
			case _, ok := <-done:
				if !ok {
					return
				}
			default:

				var f req

				if t.TaskType == RetweetType {
					f = cli.Retweeters
				} else {
					f = cli.TweetLikingUsers
				}

				users, err := page.Request(t.TaskId, "", f)

				if err != nil {
					slog.Error(" page.Request", "task id", t.TaskId, "t.TaskType", t.TaskType, "err", err.Error())
					continue
				}

				if err := InsertTaskRes(users, t.TaskType, t.TaskId); err != nil {

					for k, v := range users {
						fmt.Println(k, v.UserId, v.UserName)
					}

					slog.Error("InsertTaskRes", "task id", t.TaskId, "t.TaskType", t.TaskType, "len(users)", len(users), "err", err.Error())
				}

				slog.Info("InsertTaskRes", "task id", t.TaskId, "t.TaskType", t.TaskType, "len(users)", len(users))
			}
		}

	}()

	return done

}
