package com.cc.infosur.map;

import com.cc.infosur.R;

import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.views.MapView;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;

public class CustomMarker extends Marker {
	Paint textFillPaint = null;
	Paint rectanglePaint = null;
	String mLabel = null;
	Bitmap mPicture = null;
	private int markerType; // 0: step, 1:service, 2:flora/fauna/heritage

	public CustomMarker(MapView mapView, int type, String label,
			Bitmap picture) {
		super(mapView);
		mLabel = label;
		mPicture = picture;
		markerType = type;

		textFillPaint = new Paint();
		textFillPaint.setColor(Color.WHITE);
		textFillPaint.setTextSize(15f);
		textFillPaint.setAntiAlias(true);
		textFillPaint.setTextAlign(Paint.Align.CENTER);
		
		rectanglePaint = new Paint();
		rectanglePaint.setColor(Color.BLACK);
		rectanglePaint.setAlpha(75);
	}

	public void draw(final Canvas c, final MapView osmv, boolean shadow) {
		draw(c, osmv);
	}

	public void draw(final Canvas c, final MapView osmv) {
		super.draw(c, osmv, false);
		Point p = this.mPositionPixels; // already provisioned by Marker

		BitmapDrawable bd = (BitmapDrawable) osmv.getResources().getDrawable(
				R.drawable.mapmarker_136x110);
		int height = bd.getBitmap().getHeight();
		int width = bd.getBitmap().getWidth();
		textFillPaint.setTextSize(height / 5);

		if (mPicture != null){
            Bitmap b = Bitmap.createScaledBitmap(mPicture,136,110,false);
			c.drawBitmap(b, new Rect(0, 0, 100, 100), new Rect(p.x
					- ((width / 2) - (width / 19)), p.y
					- (height - (height / 20)) + (height / 10), p.x
					+ ((width / 2) - (width / 20)), p.y - (int) (height / 3.7)
					+ (height / 10)), null);

        }

		float widths[] = new float[mLabel.length()];
		float sumWidths = 0;
		textFillPaint.getTextWidths(mLabel, widths);
		for (int i = 0; i < mLabel.length(); i++) {
			sumWidths += widths[i];
			if (sumWidths > width) {
				mLabel = mLabel.substring(0, i - 3);
				mLabel = mLabel.concat("..");
				break;
			}
		}
		
	    c.drawRect(p.x
				- ((width / 2) - (width / 19)), p.y - (int) (height / 3), p.x
				+ ((width / 2) - (width / 20)), p.y - (int) (height / 3.7)
				+ (height / 10), rectanglePaint);
	    
		c.drawText(mLabel, p.x+2, p.y - (int) (height / 3.7) + (height / 10),
				textFillPaint);
		// c.drawText(mLabel, p.x, p.y-(int)(height/3.7), textStrokePaint);

	}

	public int getMarkerType() {
		return markerType;
	}

	public void setMarkerType(int markerType) {
		this.markerType = markerType;
	}
}
