package com.bartlomiejpluta.demo.world.time;

import DB.dao;
import com.bartlomiejpluta.base.api.context.Context;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import static java.lang.Math.max;
import static java.lang.Math.min;

public class WorldTime {
   private static final float MINUTES_PER_DAY = 1440f; // 60min * 24

   @Getter
   private float progress = 0;
   private final float period; // seconds
   private final Context context;

   public WorldTime(@NonNull Context context) {
      this.context = context;
      this.period = Float.parseFloat(dao.config.find("full_day_duration").getValue());
   }

   public void setProgress(float progress) {
      this.progress = max(0, min(1, progress));
   }

   public void setTime(@NonNull String time) {
      var splitted = time.split(":");
      this.setTime(Integer.valueOf(splitted[0], 10), Integer.valueOf(splitted[1], 10));
   }

   public void setTime(int h, int m) {
      this.progress = (h * 60 + m) / MINUTES_PER_DAY;
   }

   public int getHour() {
      return (int) (progress * 24);
   }

   public int getMinute() {
      return (int) (progress * 24 * 60) % 60;
   }

   public void update(float dt) {
      if (context.isPaused()) {
         return;
      }

      progress += dt / period;
      if (progress > 1) {
         progress = 0;
      }
   }
}
