using System.IO;
using UnityEngine;
using System.Collections.Generic;

public class Helper {
	public static Vector2 perlinOffset = new Vector2(0, 0);
	public static Vector2 perlinCoeff = new Vector2(1, 1);

	private static System.Random rand = new System.Random(0);
	private static Texture2D defaultTexture = loadTexture("Assets/Biomes/default.png");
	private static Dictionary<Color, Sprite> colorSpriteCache = new Dictionary<Color, Sprite>();

	public static float getPerlinValue(Vector2 point, Vector2 localOffset) {
		return getPerlinValue(point.x, point.y, localOffset);
	}

	public static float getPerlinValue(float x, float y, Vector2 localOffset) {
		return Mathf.PerlinNoise(x * perlinCoeff.x + perlinOffset.x + localOffset.x, y * perlinCoeff.y + perlinOffset.y + localOffset.y);
	}

	public static Texture2D loadTexture(string file) {
		if (File.Exists(file)) {
			Texture2D tex = new Texture2D(2, 2);
			if (tex.LoadImage(File.ReadAllBytes(file))) {
				return tex;
			}
		}
		return null;
	}

	public static Color getColorVariation(Color source) {
		return new Color(Mathf.Clamp01(source.r + (getRandom()-0.5f)/3), Mathf.Clamp01(source.g + (getRandom()-0.5f)/3), Mathf.Clamp01(source.b + (getRandom()-0.5f)/3));
	}

	public static Sprite loadSprite(string file) {
		Texture2D tex = loadTexture(file);
		return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height),new Vector2(0, 0), 1000);
	}

	public static Sprite spriteFromTexture(Texture2D tex) {
		return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height),new Vector2(0, 0), 1000);
	}

	public static Sprite getHexaSprite(Color color) {
		if (colorSpriteCache.ContainsKey(color)) {
			return colorSpriteCache[color];
		}
		Texture2D tex = new Texture2D(defaultTexture.width, defaultTexture.height, defaultTexture.format, defaultTexture.mipmapCount > 1);
		Graphics.CopyTexture(defaultTexture, tex);
		Color[] pixels = tex.GetPixels();
		for (int i = 0; i < pixels.Length; i++) {
			if (pixels[i].r > 0.9f) {
				pixels[i] = color;
			}
		}
		tex.SetPixels(pixels);
		tex.Apply();
		Sprite sprite = spriteFromTexture(tex);
		colorSpriteCache[color] = sprite;
		return sprite;
	}

	public static float getRandom() {
		return (float)rand.NextDouble();
	}

	public static float getNormalRandom() {
		float u0 = 1.0f - (float)rand.NextDouble();
		float u1 = 1.0f - (float)rand.NextDouble();
		return Mathf.Sqrt(-2.0f * Mathf.Log(u0)) * Mathf.Sin(2.0f * Mathf.PI * u1);
	}
}
