package com.example.fideliza;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.onbarcode.barcode.android.AndroidColor;
import com.onbarcode.barcode.android.AndroidFont;
import com.onbarcode.barcode.android.EAN13;
import com.onbarcode.barcode.android.IBarcode;

public class AndroidBarcodeView extends View {
	static String code;
	static int width_pan;
	private Context contexto;

	public AndroidBarcodeView(Context context) {
		super(context);
		contexto = context;
		setBackgroundResource(R.drawable.fondo_int);
		SharedPreferences preferencias = context.getSharedPreferences(
				"fideliza", Context.MODE_PRIVATE);
		String s = preferencias.getString("numfideliza", "");
		if (s != "") {
			code = s;
		} else {
			code = obtener_lic();
			if (code != "0") {
				SharedPreferences.Editor editor = preferencias.edit();
				editor.putString("numfideliza", code);
				editor.commit();
			}
		}
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		Point size = new Point();
		width_pan = display.getWidth();

	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		try {
			BarcodeEAN13(canvas);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String obtener_lic() {
		try {
			TareaLicencia tarea = new TareaLicencia();
			tarea.execute();
			return tarea.get(4, TimeUnit.SECONDS);
		} catch (TimeoutException e) {
			Toast.makeText(contexto, "Tiempo excedido al conectar",
					Toast.LENGTH_LONG).show();
		} catch (CancellationException e) {
			Toast.makeText(contexto, "Error al conectar con servidor",
					Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			Toast.makeText(contexto, "Error con tarea asíncrona",
					Toast.LENGTH_LONG).show();
		}
		return "0";
	}

	private class TareaLicencia extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... arg0) {
			try {
				URL url = new URL("http://www.piavant.es/licencia.php?cod=pi");
				HttpURLConnection conexion = (HttpURLConnection) url
						.openConnection();
				if (conexion.getResponseCode() == HttpURLConnection.HTTP_OK) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(conexion.getInputStream()));
					String linea = reader.readLine();
					return linea;
				} else {
					return "0";
				}
			} catch (Exception e) {
				return "0";
			}
		}
	}

	private static void BarcodeEAN13(Canvas canvas) throws Exception {
		EAN13 barcode = new EAN13();

		/*
		 * EAN 13 Valid data char set: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 (Digits)
		 * 
		 * EAN 13 Valid data length: 12 digits only, excluding the last checksum
		 * digit
		 */
		String code2 = String.format("%012d", Integer.parseInt(code));
		// barcode.setData("012345678901");
		barcode.setData(code2);
		// for EAN13 with supplement data (2 or 5 digits)
		/*
		 * barcode.setSupData("12"); // supplement bar height vs bar height
		 * ratio barcode.setSupHeight(0.8f); // space between barcode and
		 * supplement barcode (in pixel) barcode.setSupSpace(15);
		 */

		// Unit of Measure, pixel, cm, or inch
		barcode.setUom(IBarcode.UOM_PIXEL);
		// barcode bar module width (X) in pixel
		// barcode.setX(1f);
		float xval = width_pan / 100 - 1;
		barcode.setX(xval);
		// barcode bar module height (Y) in pixel
		// barcode.setY(45f);

		barcode.setY(100f);
		// barcode image margins
		barcode.setLeftMargin(10f);
		barcode.setRightMargin(10f);
		barcode.setTopMargin(10f);
		barcode.setBottomMargin(10f);

		// barcode image resolution in dpi
		barcode.setResolution(70);

		// disply barcode encoding data below the barcode
		barcode.setShowText(true);
		// barcode encoding data font style
		barcode.setTextFont(new AndroidFont("Arial", Typeface.NORMAL, 21));
		// space between barcode and barcode encoding data
		barcode.setTextMargin(6);
		barcode.setTextColor(AndroidColor.black);

		// barcode bar color and background color in Android device
		barcode.setForeColor(AndroidColor.black);
		barcode.setBackColor(AndroidColor.white);

		/*
		 * specify your barcode drawing area
		 */
		RectF bounds = new RectF(30, 30, 0, 0);
		barcode.drawBarcode(canvas, bounds);

		Paint pincel = new Paint();
		pincel.setColor(Color.BLUE);
		pincel.setStrokeWidth(2);
		// pincel.setStyle(Style.STROKE);
		pincel.setTextSize(width_pan / 10);
		canvas.drawText("Cod: " + code, 30, 250, pincel);
	}

}
