export type EncoderLanguage = 'esc-pos' | 'star-prnt' | 'star-line';

const ESC_POS_CODEPAGE_MAPPINGS = new Set([
    'bixolon/legacy',
    'bixolon',
    'citizen',
    'epson/legacy',
    'epson',
    'fujitsu',
    'hp',
    'metapace',
    'mpt',
    'pos-5890',
    'pos-8360',
    'star',
    'xprinter',
    'youku',
    'zijang',
]);

const STAR_CODEPAGE_MAPPINGS = new Set(['star']);

const CODEPAGE_ALIASES: Record<string, string> = {
    default: 'epson',
    zjiang: 'zijang',
};

export function normalizeEncoderLanguage(language?: string | null): EncoderLanguage {
    if (language === 'star-prnt' || language === 'star-line') {
        return language;
    }

    return 'esc-pos';
}

export function normalizeCodepageMapping(
    language: EncoderLanguage,
    codepageMapping?: string | null,
): string {
    const mapping = codepageMapping
        ? CODEPAGE_ALIASES[codepageMapping] ?? codepageMapping
        : 'epson';

    if (language === 'star-prnt' || language === 'star-line') {
        return STAR_CODEPAGE_MAPPINGS.has(mapping) ? mapping : 'star';
    }

    return ESC_POS_CODEPAGE_MAPPINGS.has(mapping) ? mapping : 'epson';
}

export function normalizeEncoderOptions(options?: {
    language?: string | null;
    codepageMapping?: string | null;
}): {
    language: EncoderLanguage;
    codepageMapping: string;
} {
    const language = normalizeEncoderLanguage(options?.language);

    return {
        language,
        codepageMapping: normalizeCodepageMapping(language, options?.codepageMapping),
    };
}
