#ifndef IO_BXL_BXL_H
#define IO_BXL_BXL_H

#include <genht/htsp.h>

#include <libcschem/cnc_grp.h>
#include <libcschem/cnc_poly.h>
#include <plugins/lib_alien/read_helper.h>

typedef enum {
	PCB_BXL_JUST_TOP    = 1,
	PCB_BXL_JUST_LEFT   = 1,
	PCB_BXL_JUST_CENTER = 2,
	PCB_BXL_JUST_BOTTOM = 4,
	PCB_BXL_JUST_RIGHT  = 4
} pcb_bxl_just_t;

typedef struct {
	double width, height, char_width;
} sch_bxl_text_style_t;

typedef struct sch_bxl_ctx_s {
	FILE *f;
	const char *fn;
	csch_cgrp_t *grp;
	long lineno, colno;

	unsigned silent:1;

	csch_alien_read_ctx_t alien; /* contains ->sheet */


	char in_target_sym;      /* 1 if we are parsing the target footprint; else skip */
	const char *subsymname;  /* target symboln name to load */

	int in_error;

	/* cache */
	htsp_t text_name2style;

	struct {
		rnd_coord_t origin_x, origin_y;
	} sym_state;

	struct {
		rnd_coord_t origin_x, origin_y, endp_x, endp_y, width, height, radius;
		rnd_coord_t hole;
		csch_cpoly_t *poly;
		double arc_start, arc_delta;
		double rot;
		int num_shapes, shape_type;
		long pstk_proto_id;
		char *pin_name;
		pcb_bxl_just_t hjust, vjust;
		sch_bxl_text_style_t *text_style;
		char *text_str, *attr_key, *attr_val;
		unsigned flipped:1;
		unsigned is_visible:1;
		unsigned plated:1;
		unsigned nopaste:1;
		unsigned surface:1;

		unsigned delayed_poly:1;
		unsigned is_text:1;
		unsigned has_mask_shape:1;
		int copper_shape_idx;
	} state;

	struct {
		int num;

		char *des;
		double des_x, des_y;

		char *name;
		double name_x, name_y;

		double origin_x, origin_y;
		double length, width;
		int rot, is_visible;
	} pin;

	struct {
		long poly_broken;
		long property_null_obj;
		long property_nosep;
	} warn;

} sch_bxl_ctx_t;

void sch_bxl_init(sch_bxl_ctx_t *bctx, const char *subsymname);
void sch_bxl_uninit(sch_bxl_ctx_t *bctx);


void sch_bxl_symbol_begin(sch_bxl_ctx_t *bctx, const char *name);
void sch_bxl_symbol_end(sch_bxl_ctx_t *ctx);
void sch_bxl_reset(sch_bxl_ctx_t *ctx);
void sch_bxl_reset_symbol(sch_bxl_ctx_t *ctx);
void sch_bxl_set_justify(sch_bxl_ctx_t *ctx, const char *str);
void sch_bxl_set_attr_val(sch_bxl_ctx_t *ctx, char *key, char *val);
void sch_bxl_add_line(sch_bxl_ctx_t *ctx);
void sch_bxl_add_arc(sch_bxl_ctx_t *ctx);
void sch_bxl_add_text(sch_bxl_ctx_t *ctx);
void sch_bxl_set_text_str(sch_bxl_ctx_t *ctx, char *str);
void sch_bxl_poly_begin(sch_bxl_ctx_t *ctx);
void sch_bxl_poly_add_vertex(sch_bxl_ctx_t *ctx, rnd_coord_t x, rnd_coord_t y);
void sch_bxl_poly_end(sch_bxl_ctx_t *ctx);
void sch_bxl_text_style_begin(sch_bxl_ctx_t *ctx, char *name);
void sch_bxl_text_style_end(sch_bxl_ctx_t *ctx);
void sch_bxl_set_text_style(sch_bxl_ctx_t *ctx, const char *name);
void sch_bxl_set_text_style_ref(sch_bxl_ctx_t *ctx, const char *name);

void sch_bxl_pin_begin(sch_bxl_ctx_t *ctx);
void sch_bxl_pin_des(sch_bxl_ctx_t *ctx, char *des, double x, double y);
void sch_bxl_pin_name(sch_bxl_ctx_t *ctx, char *name, double x, double y);
void sch_bxl_pin_end(sch_bxl_ctx_t *ctx);

#endif
