package hh.michelson;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import hh.lib.D;

public class GraphView extends View {
	D d;
	Context context;
	Paint mPaint;
	float[] graphValues = new float[] {0f};
	float[] graphLines = null;
	int W = 0, H, Y0;
	final int maxH = 600;
	double maxY = 0d;
	double dx;
	double kY;

	/*GraphView(Context context) {
		super(context);
		init(context); }*/

	public GraphView(Context context, AttributeSet a) {
		super(context, a);
		init(context); }

	/*GraphView(Context context, AttributeSet a, int defStyleAttr) {
		super(context, a, defStyleAttr);
		init(context); }

	GraphView(Context context, AttributeSet a, int defStyleAttr, int defStyleRes) {
		super(context, a, defStyleAttr, defStyleRes);
		init(context); }*/

	void init(Context context) {
		this.d = ((A)context).d.klon(this);
		this.context = context;
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setStyle(Paint.Style.FILL);
		mPaint.setColor(Color.RED);}

	public void onDraw(Canvas canvas) {
		d.l(4, "graph.onDraw");
		canvas.drawLine(0, Y0, W, Y0, mPaint);
		fillGraphArray();
		if(graphLines != null) canvas.drawLines(graphLines, mPaint);
	}

	void setGraphValues(float[] graphValues) { this.graphValues = graphValues; }

    void setMaxY(double maxY) { this.maxY = maxY; }

	protected void onMeasure(int w, int h) {
		W = MeasureSpec.getSize(w);
		H = MeasureSpec.getSize(h) > maxH ? maxH : MeasureSpec.getSize(h);
		super.onMeasure(w, h);
		setMeasuredDimension(W, H);
		Y0 = H / 2;
		if(d.ll(4)) d.l(String.format(A.lo, "graph, onMeasure, w=%d, W=%d, h=%d, H=%d, Y0=%d",
				MeasureSpec.getSize(w), W, MeasureSpec.getSize(h), H, Y0));
	}

	void fillGraphArray() {
		if(d.ll(4)) d.l(String.format(A.lo, "fillGraphArray, W=%d, graphValues.length=%d", W, graphValues.length));
		graphLines = null;
		if(W > 0 && graphValues != null) {
			dx = (double)W / graphValues.length;
			kY = 4.0 * Y0 / (5.0 * maxY);
			graphLines = new float[4 * graphValues.length];
			graphLines[0] = 0;
			graphLines[1] = Y0;
			if(d.ll(4)) d.l(String.format(A.lo, "W=%d, H=%d, Y0=%d, graphLines.length=%d", W, H, Y0, graphLines.length));
			int i = 0;
			for(double v: graphValues) {
				if(i > 0) {
					graphLines[i] = graphLines[i-2];
					graphLines[i+1] = graphLines[i-1];
				}
				graphLines[i+2] = graphLines[i] + Double.valueOf(dx).floatValue();
				graphLines[i+3] = Double.valueOf(Y0 - kY * v).floatValue();
				i += 4;
			}
			graphLines[0] = graphLines[2];
			graphLines[1] = graphLines[3];
		}
	}
}
