package bj.pranie;

import bj.pranie.dao.ReservationDao;
import bj.pranie.entity.User;
import bj.pranie.entity.myEnum.UserRole;
import bj.pranie.service.UserServiceImpl;
import bj.pranie.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

/**
 * Created by Sebastian Sokolowski on 13.09.17.
 */
@SpringBootApplication
public class Application {
    static Logger log = Logger.getLogger(Application.class.getName());

    private final static int RESET_TIME = 10;

    @Autowired
    private UserServiceImpl userService;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @PostConstruct
    public void init() {
        startTimerToResetUsersTokens();
    }

    private void startTimerToResetUsersTokens() {
        Calendar nowCalendar = TimeUtil.getCalendar();

        Calendar nextReset = TimeUtil.getCalendar();
        nextReset.set(Calendar.HOUR_OF_DAY, RESET_TIME);
        nextReset.set(Calendar.MINUTE, 0);
        nextReset.set(Calendar.SECOND, 0);

        while (nextReset.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
            nextReset.add(Calendar.DAY_OF_WEEK, 1);
        }
        long delay = nextReset.getTimeInMillis() - nowCalendar.getTimeInMillis();

        float hourDelay = (delay / (float) (1000 * 60 * 60 * 24));
        log.info("Delay to start reset users tokens: " + hourDelay + " days.");
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                resetUsersTokens();
            }
        }, delay);
    }

    private void resetUsersTokens() {
        Iterable<User> iterable = userService.findAll();
        Iterator<User> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            User user = iterator.next();
            if (user.getRole() == UserRole.USER) {
                user.setTokens(2);
            }
        }

        userService.save(iterable);
    }
}

@@ -17,45 +17,8 @@
 e;%0A%0A
-import bj.pranie.dao.ReservationDao;%0A
 impo
@@ -1313,23 +1313,33 @@
         
-while (
+do %7B%0A            
 nextRese
@@ -1340,19 +1340,19 @@
 xtReset.
-get
+add
 (Calenda
@@ -1368,44 +1368,31 @@
 WEEK
-) != Calendar.SUNDAY) %7B%0A            
+, 1);%0A        %7D while (
 next
@@ -1389,35 +1389,35 @@
 hile (nextReset.
-add
+get
 (Calendar.DAY_OF
@@ -1421,31 +1421,39 @@
 _OF_WEEK
-, 1);%0A        %7D
+) != Calendar.SUNDAY);%0A
 %0A       

FIx negative delay.