/*
 * libptouch — current tape/media information helper
 *
 * Author: knb
 * Email: knb@artif.org
 */

#include "libptouch_internal.h"
#include "libptouch_layout.h"

#include <string.h>

static double tape_width_mm_from_code(uint8_t media_w)
{
	switch (media_w) {
	case 0x04:
		return 3.5;
	case 0x06:
		return 6.0;
	case 0x09:
		return 9.0;
	case 0x0C:
		return 12.0;
	case 0x12:
		return 18.0;
	case 0x18:
		return 24.0;
	case 0x24:
		return 36.0;
	case 0x15:
		return 21.0; /* FLe width code */
	default:
		return 0.0;
	}
}

static double print_dpi_from_profile(const ptouch_printer_profile_t *prof)
{
	if (!prof)
		return 0.0;
	if (prof->head_width_dots <= 128u)
		return 180.0;
	return 360.0;
}

libptouch_err_t libptouch_get_current_media_info(libptouch_ctx *ctx,
						 libptouch_media_info_t *out_info)
{
	if (!ctx || !out_info) {
		if (ctx)
			ptouch_set_error(ctx, LIBPTOUCH_ERR_ARG, "null argument");
		return LIBPTOUCH_ERR_ARG;
	}

	memset(out_info, 0, sizeof(*out_info));

	uint8_t st[LIBPTOUCH_STATUS_LENGTH];
	libptouch_err_t v = libptouch_get_status(ctx, st);
	if (v != LIBPTOUCH_OK)
		return v;

	const ptouch_printer_profile_t *prof =
		ptouch_layout_resolve_profile(ctx->usb_pid, st[4]);
	if (!prof) {
		ptouch_set_error(ctx, LIBPTOUCH_ERR_UNSUPPORTED,
				 "no layout profile for this printer");
		return LIBPTOUCH_ERR_UNSUPPORTED;
	}

	uint16_t left_dots = 0, print_dots = 0, right_dots = 0;
	v = ptouch_layout_from_status(prof, st[11], st[10], &left_dots,
				      &print_dots, &right_dots);
	if (v != LIBPTOUCH_OK) {
		ptouch_set_error(ctx, LIBPTOUCH_ERR_UNSUPPORTED,
				 "tape width/layout not supported for this media");
		return LIBPTOUCH_ERR_UNSUPPORTED;
	}

	double tape_mm = tape_width_mm_from_code(st[10]);
	if (tape_mm <= 0.0) {
		ptouch_set_error(ctx, LIBPTOUCH_ERR_UNSUPPORTED,
				 "unknown tape width code");
		return LIBPTOUCH_ERR_UNSUPPORTED;
	}

	out_info->media_width_code = st[10];
	out_info->media_kind_code = st[11];
	out_info->print_dpi = print_dpi_from_profile(prof);
	out_info->feed_dpi = prof->margin_feed_dpi;
	out_info->tape_width_mm = tape_mm;
	out_info->printable_dots = print_dots;
	out_info->left_margin_dots = left_dots;
	out_info->right_margin_dots = right_dots;
	out_info->min_feed_dots = 14u;
	out_info->min_feed_mm =
		((double)out_info->min_feed_dots * 25.4) / prof->margin_feed_dpi;

	ptouch_set_error(ctx, LIBPTOUCH_OK, "");
	return LIBPTOUCH_OK;
}
