import axios from "axios";
import {blue100} from "react-native-paper/lib/typescript/styles/themes/v2/colors";

class PrintingService {
    private static instance: PrintingService | null = null;
    private readonly apiUrl: string;
    private readonly port: number;

    public static getInstance(port?: number): PrintingService {
        if (!this.instance) {
            this.instance = new PrintingService(port);
        }
        return this.instance;
    }

    private constructor(port = 2282) {
        this.apiUrl = "127.0.0.1";
        this.port = port;
    }

    private newAbortSignal(timeoutMs: number) {
        const abortController = new AbortController();
        setTimeout(() => abortController.abort(), timeoutMs || 0);

        return abortController.signal;
    }

    private async print(printer: string, type: string, bytes: Uint8Array): Promise<boolean> {
        try {
            let response = await axios.post(`http://${this.apiUrl}:${this.port}/print/${printer}/${type}`, bytes.buffer, {
                timeout: 25 * 1000,
                signal: this.newAbortSignal(25 * 1000)
            });
            return response.data.ok;
        } catch (error) {
            console.log(error);
            return false;
        }
    }

    public async printPdf(printer: string, pdfBytes: Uint8Array): Promise<boolean> {
        return this.print(printer, "pdf", pdfBytes);
    }

    public async printImage(printer: string, imageBytes: Uint8Array): Promise<boolean> {
        return this.print(printer, "image", imageBytes);
    }

    public getPrinter(baseMarketplace: number): string {
        if (baseMarketplace == 0) return "wildberries";
        return "ozon";
    }
}

export default PrintingService;