package com.example.sample;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.View;

public class ImageView extends View {
	// 部分イメージの配列
	private Bitmap [][] imgArray;
	// 描画する点の集合
	private ArrayList<Atom> atomArray;
	// 描画設定
	private Paint paint = new Paint();

	public ImageView (Context context) {
		super(context);
	
		initAtoms();
	}

	//描画処理
	@Override
	public void onDraw(Canvas canvas) {
		paint.setColor(Color.CYAN);
		for (int i = 0; i < atomArray.size(); i++) {
			Atom atom = atomArray.get(i);
			canvas.drawCircle(atom.x, atom.y, ATOM_WIDTH, paint);
		}
	}
	
	/********************************/
	/* 部分イメージをロード */
	/********************************/
	public Bitmap loadSubImage(int x, int y) throws FileNotFoundException, IOException {
		Resources res = this.getContext().getResources();
		int resId = getResources().getIdentifier("neko"+String.valueOf(x)+String.valueOf(y),"drawable",this.getContext().getPackageName());
		Bitmap bmp = BitmapFactory.decodeResource(res, resId);
		return bmp;
	}

	private static final int TILE_COLUMNS = 32;
	private static final int TILE_ROWS = 32;
	public Bitmap[][] loadAllSubImage() {
		imgArray = new Bitmap[TILE_ROWS][TILE_COLUMNS]; // int[x][y]

		try {
			for (int x = 0; x < TILE_COLUMNS; x++) {
				for (int y = 0; y < TILE_ROWS; y++) {
						imgArray[x][y] = loadSubImage(x, y);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return imgArray;
	}
	
	/* イメージが黒っぽいか判定 */
	private static final long POINT_THRESHOLD = 1000000000;
	public static boolean isBlackImage(Bitmap img) {
		int w = img.getWidth();
		int h = img.getHeight();
		
		long point = 0;
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				int rgb = img.getPixel(x, y) & 0x00ffffff;
				
				point += rgb;
			}
		}
		Log.v("subimg", "point:" + point);

		// pointが低いと黒っぽい
		if (point < POINT_THRESHOLD) {
			return true;
		}
		
		return false;
	}

	/* 黒っぽいイメージの座標取得 */
	private static final int ATOM_WIDTH = 6;
	private static final int ATOM_HEIGHT = 6;
	public void initAtoms() {
		imgArray = loadAllSubImage();
		int columns = imgArray.length;
		int rows = imgArray[0].length;
		atomArray = new ArrayList<Atom>();
		
		for (int x = 0; x < columns; x++) {
			for (int y = 0; y < rows; y++) {
				if (isBlackImage(imgArray[x][y])) {
					atomArray.add(new Atom(x * ATOM_WIDTH + x * 10, y * ATOM_HEIGHT + y * 10));
				}
			}
		}
	}

}

