package mior.model;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;

import javax.imageio.ImageIO;

import mior.model.dist.IMiorDistribution;

public class MiorUtils {
	
	private static Random rand = new Random();
	
	public static void initRandomMMArray(MiorMM[] mmList, int width) {
		for (int i = 0; i < mmList.length; i++) {
			mmList[i] = new MiorMM(
					rand.nextFloat() * width,
					rand.nextFloat() * width
			);
		}
	}
	
	public static void initRandomOMArray(MiorOM[] omList, int width) {
		for (int i = 0; i < omList.length; i++) {
			omList[i] = new MiorOM(
					rand.nextFloat() * width,
					rand.nextFloat() * width
			);
		}
	}
	
	@Deprecated
	public static MiorMM createMM(MiorWorld world) {
		return new MiorMM(
				rand.nextFloat() * world.width,
				rand.nextFloat() * world.width
		);
	}
	
	@Deprecated
	public static MiorOM createOM(MiorWorld world) {
		return new MiorOM(
				rand.nextFloat() * world.width,
				rand.nextFloat() * world.width
		);
	}
	
	@Deprecated
	public static MiorMM[] allocMMArray(MiorWorld world) {
		MiorMM[] mmList = new MiorMM[world.nbMM];
		initMMArray(world, mmList);
		return mmList;
	}
	
	@Deprecated
	public static void initMMArray(MiorWorld world, IMiorMM [] mmList) {
		for (int i = 0; i < mmList.length; i++) {
			mmList[i] = createMM(world);
		}
	}
	
	@Deprecated
	public static MiorOM[] allocOMArray(MiorWorld world) {
		MiorOM[] omList = new MiorOM[world.nbOM];
		initOMArray(world, omList);
		return omList;
	}
	
	@Deprecated
	public static void initOMArray(MiorWorld world, IMiorOM [] omList) {
		for (int i = 0; i < omList.length; i++) {
			omList[i] = createOM(world);
		}
	}
	
	public static void initWorldArray(MiorWorld [] worldList, IMiorDistribution dist) {
		for (int i = 0; i < worldList.length; i++) {
			worldList[i] = new MiorWorld(dist.getMeanMM(), dist.getMeanOM(), dist.getFactor());
		}
	}
	
	public static int[] allocateCSRStorage(int size, int capacity) {
		int [] result = new int[1 + size * (capacity + 1)];
		result[0] = capacity;
		return result;
	}
	
	public static void initAssociations(int [] associations) {
		Arrays.fill(associations, -1);
	}
	
	public static void initCSRStorage(int [] csrStorage) {
		Arrays.fill(csrStorage, 1, csrStorage.length, 0);
	}
	
	public static void saveTopoAs(IMiorModel model, File path) {
		final int nbMM = model.getMMList().length;
		final int nbOM = model.getOMList().length;
		
		BufferedImage img = new BufferedImage(nbMM, nbOM, BufferedImage.TYPE_INT_ARGB);
		
		for (int iMM = 0; iMM < nbMM; iMM++) {
			for (int iOM = 0; iOM < nbOM; iOM++) {
				if (model.isAccessible(iMM, iOM)) {
					img.setRGB(iMM, iOM, 255);
				} else {
					img.setRGB(iMM, iOM, 0);
				}
			}
		}
		
		try {
		    ImageIO.write(img, "png", path);
		} catch (IOException e) {
		    System.err.println(e);
		}
	}
}
