<?php

namespace WPDesk\FakturyKSEF\Xml\Validators;

use LibXMLError;

class Error {

	public int $code;

	public string $field_name;

	public string $message;

	public string $translate_message;

	public function __construct( LibXMLError $error ) {
		$this->set_code( $error->code );
		$this->set_translate_message( $error->code );
		$this->set_message( trim( $error->message ) );
		$this->set_field_name( $this->get_field_name_from_message( trim( $error->message ) ) );
	}

	public function set_field_name( string $message ): void {
		$this->field_name = $message;
	}

	public function get_field_name(): string {
		return $this->field_name;
	}

	public function set_code( int $code ): void {
		$this->code = $code;
	}

	public function get_code(): int {
		return $this->code;
	}

	private function get_field_name_from_message( string $message ): string {
		preg_match( '/\'{.+}(.*)\':/i', $message, $output_array );
		if ( isset( $output_array[1] ) ) {
			return $output_array[1];
		}

		return __( 'Unknown field', 'ksef-for-flexible-invoices' );
	}

	public function set_message( string $message ): void {
		$this->message = $message;
	}

	public function get_message(): string {
		return $this->message;
	}


	public function set_translate_message( int $code ): void {
		$this->translate_message = ErrorMessageFactory::get_message( $code );
	}

	public function get_translate_message(): string {
		return $this->translate_message;
	}
}
