package zero1hd.rhythmbullet.util;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.resolvers.ResolutionFileResolver.Resolution;
import com.badlogic.gdx.files.FileHandle;

public class RoundingResolutionHandler implements FileHandleResolver {
	private final Resolution[] descriptors;
	private final FileHandleResolver resolver;
	private boolean silent = true;
	private int width, height;
	public RoundingResolutionHandler(FileHandleResolver fileResolver, Resolution... descriptors) {
		if (descriptors.length == 0) throw new IllegalArgumentException("At least one Resolution needs to be supplied.");
		this.descriptors = descriptors;
		this.resolver = fileResolver;
	}
	
	public void setResolution(int width, int height) {
		this.width = width;
		this.height = height;
	}
	
	public void resetResolution() {
		width = Gdx.graphics.getWidth();
		height = Gdx.graphics.getHeight();
	}
	
	public Resolution chooseRounded(Resolution... descriptors) {
		Resolution best = descriptors[0];
		
		int leastDifference = -1;
		
		int w = width, h = height;
		
		if (w > h) {
			for (int i = 0; i < descriptors.length; i++) {
				int currentDiff = h - descriptors[i].portraitHeight;
				
				if (currentDiff < 0) {
					currentDiff = currentDiff*-1;
				}
				
				if ((currentDiff < leastDifference) || leastDifference == -1) {
					best = descriptors[i];
					leastDifference = currentDiff;
				}
			}
		} else {
			for (int i = 0; i < descriptors.length; i++) {
				int currentDiff = w - descriptors[i].portraitWidth;
				
				if (currentDiff < 0) {
					currentDiff = currentDiff*-1;
				}
				
				if (currentDiff < leastDifference || leastDifference == -1) {
					best = descriptors[i];
					leastDifference = currentDiff;
				}
			}
		}
		return best;
	}

	@Override
	public FileHandle resolve(String fileName) {
		Resolution bestRes = chooseRounded(descriptors);
		if (!silent) {
			Gdx.app.debug("RResolution Handler", "Finding best match for resolution: " + width + "x" + height + " for file: " + fileName);
			Gdx.app.debug("RResolution Handler", "Selected folder: " + bestRes.folder);
		}
		FileHandle resSpecificFile = resolver.resolve(bestRes.folder + "/" + fileName);
		if (!resSpecificFile.exists()) resSpecificFile = resolver.resolve(fileName);
		return resSpecificFile;
	}
}
