package org.ourfilesystem.core;

import java.util.Date;

public class AutoUpdater implements Runnable {
	
	private boolean Run;
	private CoreUserInterface Core;
	private boolean AutoPeerUpdate;
	private int PeerUpdatePeriod;
	private boolean AutoPostUpdate;
	private int PostUpdatePeriod;
	
	private long LastPostUpdate = 0L;
	private long LastPeerUpdate = 0L;
	
	public AutoUpdater(CoreUserInterface core, boolean peerup, int peermin, boolean postup, int postmin) {
		Core = core;
		Run = true;
		AutoPeerUpdate = peerup;
		AutoPostUpdate = postup;
		PeerUpdatePeriod = peermin;
		PostUpdatePeriod = postmin;
		Thread t = new Thread(this);
		t.start();
	}
	
	public synchronized void Close() {
		Run = false;
		notifyAll();
	}
	
	private long min2ms(int min) {
		return ((long)min) * 60L * 1000L;
	}
	
	private synchronized void Wait() {
		if (AutoPeerUpdate || AutoPostUpdate) {
			long wt = 0L;
			if (AutoPeerUpdate) {
				wt = min2ms(PeerUpdatePeriod);
			}
			if (AutoPostUpdate) {
				wt = min2ms(PostUpdatePeriod);
			}
			if (AutoPeerUpdate && AutoPostUpdate) {
				int m = Math.min(PostUpdatePeriod, PeerUpdatePeriod);
				wt = min2ms(m);
			}
			if (wt == 0) { wt = 30L * 60L * 1000L; }
			try {
				wait(wt);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		else {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void Process() {
		long curtime = (new Date()).getTime();
		if (AutoPeerUpdate) {
			long tdiff = curtime - LastPeerUpdate;
			if (tdiff >= min2ms(PeerUpdatePeriod)) {
				LastPeerUpdate = curtime;
				Core.updatePeers();
			}
		}
		if (AutoPostUpdate) {
			long tdiff = curtime - LastPostUpdate;
			if (tdiff >= min2ms(PostUpdatePeriod)) {
				LastPostUpdate = curtime;
				Core.updatePosts();
			}
		}
	}
	
	public synchronized void setAutoPeerUpdate(boolean val) {
		AutoPeerUpdate = val;
		notifyAll();
	}

	public synchronized void setAutoPostUpdate(boolean val) {
		AutoPostUpdate = val;
		notifyAll();
	}
	
	public synchronized void setPeerUpdatePeriod(int min) {
		PeerUpdatePeriod = min;
		notifyAll();
	}
	
	public synchronized void setPostUpdatePeriod(int min) {
		PostUpdatePeriod = min;
		notifyAll();
	}

	@Override
	public void run() {
		while (Run) {
			Process();
			Wait();
		}
	}
	

}
