package com.sifang.modules.taskdispatch.service.autod;

import com.sifang.modules.config.SfCacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Lazy(false)
public class ItemTaskEventBus {

    private static final ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
    private static final Logger log = LoggerFactory.getLogger(ItemTaskEventBus.class);

    @Autowired
    SfCacheService sfCacheService;

    @Autowired
    ItemAutoDispatchService itemAutoDispatchService;

    public static final String TASK_NOTIFY_KEY = "event:task_finish_users";
    public static final String TASK_DISPATCHED = "event:task_dispatched:";

    public void notifyItemTaskFinish(String userId) {
        ex.schedule(new Runnable() {
            @Override
            public void run() {
                sfCacheService.lpush(TASK_NOTIFY_KEY, userId);
            }
        }, 3, TimeUnit.SECONDS);
    }

    public void notifyTaskItemDispatched(String memberId, Date time) {
        ex.submit(new Runnable() {
            @Override
            public void run() {
                sfCacheService.setex(TASK_DISPATCHED + memberId, 3600 * 24 * 2, String.valueOf(time.getTime()));
            }
        });
    }

    public void notifyUserSignIn(String userId) {
        ex.submit(new Runnable() {
            @Override
            public void run() {
                sfCacheService.lpush(TASK_NOTIFY_KEY, userId);
            }
        });
    }

    @PostConstruct
    public void init() {
        sfCacheService.del(TASK_NOTIFY_KEY);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    List<String> userIds = sfCacheService.brpop(TASK_NOTIFY_KEY, 30);
                    try {
                        if (!CollectionUtils.isEmpty(userIds)) {
                            log.info("pop user ids:{}", userIds);
                            itemAutoDispatchService.dispatch(Collections.singletonList(userIds.get(1)));
                        }
                    } catch (Exception e) {
                        log.error("dispatch loop error:{}", e.getMessage());
                    }
                }
            }
        }).start();
    }

}
