package devices.LEDMax7219;

import com.sun.jna.Memory;
import com.sun.jna.Pointer;

import anywheresoftware.b4a.BA;

@BA.ShortName("Graphic_Max7219")
public class Graphic_Max7219 {
	private Pointer mem;
	private final int blocks;
	private final int size;
	private final LEDBlock[][] ledblock;
	
	
	/**
	 * Initialize 1 block 8x8 pixel
	 */
	public Graphic_Max7219() {
		this.blocks = 1;
	
		this.size = this.blocks * 8;
		mem = new Memory(this.size);
		
		ledblock = new LEDBlock[1][1];
		ledblock[0][0] = new LEDBlock();
		
		for(int ii=0;ii<8;ii++) {
			ledblock[0][0].setpointer(ii, mem.getPointer(ii));	
		}
		
	}
	
	/**
	 * Initialize n block 8x8 pixel, dianggap 1 row dan n column
	 * @param blocks : banyaknya block, dianggap sebagai column
	 */
	public Graphic_Max7219(int blocks) {
		
		this.blocks = blocks>0 ? blocks : 1;
		this.size = this.blocks * 8; 
		mem = new Memory(this.size);
		BA.Log("MemSize = "+this.size);
		
		ledblock = new LEDBlock[blocks][1];
		for(int ii=0;ii<blocks;ii++) {
			ledblock[ii][0] = new LEDBlock();
			for(int jj=0;jj<8;jj++) {
				int memindex = jj*blocks + ii;
				ledblock[ii][0].setpointer(jj, mem.share(memindex));
			}
		}
	}
	
	/**
	 * Set All bytes to OFF (0x00)
	 */
	public void All_OFF() {
		if (mem!=null) {
			for (int ii=0;ii<size;ii++) mem.setByte(ii, (byte)0);
		}
	}
	
	/**
	 * Set all bytes to ON (0xFF)
	 */
	public void All_ON() {
		if (mem!=null) {
			for(int ii=0;ii<size;ii++) mem.setByte(ii, (byte) 0xFF);
		}
	}
	
	/**
	 * How many blocks 
	 * @return number of block, minimum is 1
	 */
	public int getBlocks() {
		return blocks;
	}
	
//	@BA.Hide
//	/**
//	 * Get short(16 bits) from specific block number
//	 * 1 short = [row code] [row bytes]
//	 * @param blocknumber : start from 0, until (getBlocks() -1)
//	 * @return short array, or null if invalid blocknumber
//	 */
//	public short[] GetBlockBytes(int blocknumber) {
//		if (blocknumber<0) return null;
//		if (blocknumber > (blocks-1)) return null;
//		if (mem==null) return null;
//		
//		short[] result = new short[8];
//		for(int ii=0;ii<8;ii++) {
//			int tmp = get_mask(ii) | (mem.getByte(ii*blocks + blocknumber) & 0xFF);
//			result[ii] = (short)tmp;
//		}
//		return result;
//	}
	
	
	public LEDBlock GetLEDBlock(int x, int y) {
		return ledblock[x][y];
	}
	
	
	
	
}
