/** Notifikace pro gotify*/
import { ClientData, GotifyServer, NotififaceInput, NotifikaceData } from '../../types';
import axios, { AxiosError } from 'axios';
import dotenv from 'dotenv';
import path from 'path';
import { getToday } from "./service";
import { formatDate, getUsersByLocation } from "./utils";
import getStorage from "./storage";

const storage = getStorage();
const ENVIRONMENT = process.env.NODE_ENV || 'production'
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });

const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
    if (!Array.isArray(gotifyServers)) {
        return []
    }
    const urls = gotifyServers.flatMap(gotifyServer =>
        gotifyServer.api_keys.map(apiKey => `${gotifyServer.server}/message?token=${apiKey}`));

    const dataPayload = {
        title: "Luncher",
        message: `${data.udalost} - spustil:${data.user}`,
        priority: 7,
    };

    const headers = { "Content-Type": "application/json" };

    const promises = urls.map(url =>
        axios.post(url, dataPayload, { headers }).then(response => {
            response.data = {
                success: true,
                message: "Notifikace doručena",
            };
            return response;
        }).catch(error => {
            if (axios.isAxiosError(error)) {
                const axiosError = error as AxiosError;
                if (axiosError.response) {
                    axiosError.response.data = {
                        success: false,
                        message: "fail",
                    };
                    console.log(error)
                    return axiosError.response;
                }
            }
            // Handle unknown error without a response
            console.log(error, "unknown error");
        })
    );
    return promises;
};

export const ntfyCall = async (data: NotififaceInput) => {
    const url = process.env.NTFY_HOST
    const username = process.env.NTFY_USERNAME;
    const password = process.env.NTFY_PASSWD;
    if (!url) {
        console.log("NTFY_HOST není definován v env")
        return
    }
    if (!username) {
        console.log("NTFY_USERNAME není definován v env")
        return
    }
    if (!password) {
        console.log("NTFY_PASSWD není definován v env")
        return
    }
    const today = formatDate(getToday());
    let clientData: ClientData = await storage.getData(today);
    const userByCLocation = getUsersByLocation(clientData.choices, data.user)

    const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
    const promises = userByCLocation.map(async user => {
        try {
            // Odstraníme mezery a diakritiku a převedeme na lowercase
            const topic = user.normalize('NFD').replace(' ', '').replace(/[\u0300-\u036f]/g, '').toLowerCase();
            const response = await axios({
                url: `${url}/${topic}`,
                method: 'POST',
                data: `${data.udalost} - spustil:${data.user}`,
                headers: {
                    'Authorization': `Basic ${token}`,
                    'Tag': 'meat_on_bone'
                }
            });
            console.log(response.data);
        } catch (error) {
            console.error(error);
        }
    })

    return promises;

}
/** Zavolá notifikace na všechny konfigurované způsoby notifikace, přetížení proměných na false pro jednotlivé způsoby je vypne*/
export const callNotifikace = async ({ input, teams = true, gotify = false, ntfy = true }: NotifikaceData) => {
    const notifications = [];
    if (ntfy) {
        const ntfyPromises = await ntfyCall(input);
        if (ntfyPromises) {
            notifications.push(...ntfyPromises);
        }
    }
    /* Zatím není
    if (teams) {
         notifications.push(teamsCall(input));
     }*/

    // Add more notifications as necessary

    //gotify bych řekl, že už je deprecated
    if (gotify) {
        const gotifyPromises = await gotifyCall(input, gotifyData);
        notifications.push(...gotifyPromises);
    }

    try {
        const results = await Promise.all(notifications);
        return results;
    } catch (error) {
        console.error("Error in callNotifikace: ", error);
        // Handle the error as needed
    }
};