using System;
using System.IO;
using System.Threading;
using UnityEngine;

namespace AllocsFixes.MapRendering
{
	public class MapRenderBlockBuffer
	{
		private int zoomLevel;
		private string currentBlockMap = string.Empty;
		private Texture2D blockMap = new Texture2D (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE);
		private Texture2D zoomBuffer = new Texture2D (1, 1);
		private Color nullColor = new Color (0, 0, 0, 0);
		private AllocsFixes.FileCache.MapTileCache cache;

		public MapRenderBlockBuffer (int level, AllocsFixes.FileCache.MapTileCache cache)
		{
			zoomLevel = level;
			this.cache = cache;
		}

		public void ResetBlock ()
		{
			currentBlockMap = string.Empty;
		}

		public void SaveBlock ()
		{
			try {
				if (currentBlockMap.Length > 0)
					saveTextureToFile (currentBlockMap);
			} catch (Exception e) {
				Log.Out ("Exception in MapRenderBlockBuffer.SaveBlock(): " + e);
			}
		}

		public bool LoadBlock (Vector2i block)
		{
			bool res = false;
			lock (blockMap) {
				string folder = Constants.MAP_DIRECTORY + "/" + (zoomLevel) + "/" + block.x;
				string fileName = folder + "/" + block.y + ".png";
				Directory.CreateDirectory (folder);
				if (!fileName.Equals (currentBlockMap)) {
					res = true;
					SaveBlock ();
					loadTextureFromFile (fileName);
				}
				currentBlockMap = fileName;
			}
			return res;
		}

		public void SetPart (Vector2i offset, int partSize, Color[] pixels)
		{
			blockMap.SetPixels (offset.x, offset.y, partSize, partSize, pixels);
		}

		public Color[] GetHalfScaled ()
		{
			zoomBuffer.Resize (Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE);
			zoomBuffer.SetPixels (blockMap.GetPixels ());

			TextureScale.Point (zoomBuffer, Constants.MAP_BLOCK_SIZE / 2, Constants.MAP_BLOCK_SIZE / 2);

			return zoomBuffer.GetPixels ();
		}

		private void loadTextureFromFile (string _fileName)
		{
			byte[] array = cache.LoadTile (zoomLevel, _fileName);
			if (array != null) {
				blockMap.LoadImage (array);
			} else {
				//try {
				//byte[] array = File.ReadAllBytes (_fileName);
				//blockMap.LoadImage (array);
				//} catch (Exception) {
				for (int x = 0; x < Constants.MAP_BLOCK_SIZE; x++) {
					for (int y = 0; y < Constants.MAP_BLOCK_SIZE; y++) {
						blockMap.SetPixel (x, y, nullColor);
					}
				}
			}
		}

		private void saveTextureToFile (string _fileName)
		{
			byte[] array = blockMap.EncodeToPNG ();
			cache.SaveTile (zoomLevel, array);
//			try {
//				byte[] array = blockMap.EncodeToPNG ();
//				File.WriteAllBytes (_fileName, array);
//			} catch (Exception e) {
//				Log.Out ("Exception in MapRenderBlockBuffer.saveTextureToFile(): " + e);
//			}
		}

	}
}
