package com.juick.components;

import com.juick.components.service.TokenService;
import com.notnoop.apns.ApnsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * Created by vitalyster on 22.11.2016.
 */
@Component
public class CleanUp {

    private static Logger logger = LoggerFactory.getLogger(CleanUp.class);

    @Inject
    ApnsService apns;
    @Inject
    TokenService tokenService;

    @Inject
    Notifications push;

    @Scheduled(fixedRate = 600000)
    public void cleanupTokens() {
        logger.info("initializing apns tokens cleanup");
        Collection<String> devices = apns.getInactiveDevices().keySet();
        int count = devices.size();
        if (count > 0) {
            logger.info("{} tokens to delete", count);
            tokenService.deleteTokens("apns", devices.stream().collect(Collectors.toList()));
        } else {
            logger.debug("No APNS tokens to delete");
        }
        logger.debug("initializing GCM tokens cleanup: {} tokens", push.getInvalidGCMTokens().size());
        tokenService.deleteTokens("gcm", push.getInvalidGCMTokens().stream().collect(Collectors.toList()));
        push.cleanupGCMTokens();
        logger.debug("initializing MPNS tokens cleanup: {} tokens", push.getInvalidMPNSTokens().size());
        tokenService.deleteTokens("mpns", push.getInvalidMPNSTokens().stream().collect(Collectors.toList()));
        push.cleanupMPNSTokens();
    }
}