import axios from "axios";
import FormData from 'form-data'

const API_URL = "https://testowe.zikor.pl/api/v1";

// const API_URL = "http://172.20.10.2:8080/api/v1";

export async function listNotices() {
    const response = await fetch(`${API_URL}/notices/get/all`);
    const data = await response.json();
    if (!response.ok) {
        throw new Error(response.toString());
    }
    return data;
}

export async function getNoticeById(noticeId) {
    const response = await fetch(`${API_URL}/notices/get/${noticeId}`);

    const data = await response.json();
    if (!response.ok) {
        throw new Error("Error");
    }
    return data;
}

export async function createNotice(notice) {
    try {
        const response = await axios.post(`${API_URL}/notices/add`, notice, {
            headers: {
                "Content-Type": "application/json",
            },
        });
        // console.log("Response", response.data, "status code: ", response.status);
        // console.log("New notice id: ", response.data.noticeId);
        // console.log("Image url: ", notice.image)

        if (response.data.noticeId !== null) {
            notice.image.forEach(imageUri => {
                uploadImage(response.data.noticeId, imageUri);
            });
            // uploadImage(response.data.noticeId, notice.image);
        }

    } catch (error) {
        console.log("Error", error.response.data, error.response.status);
    }
}

export async function getImageByNoticeId(noticeId) {
    let imageUrl;
    try {
        const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);

        const imageName = listResponse.data[0];
        imageUrl = `${API_URL}/images/get/${imageName}`;

        console.log(`Pobrano zdjęcie o nazwie: ${imageName}`);

        return imageUrl;
    } catch (err) {
        console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
        imageUrl = "https://http.cat/404.jpg";
        return imageUrl;
    }
}

export const uploadImage = async (noticeId, imageUri) => {
    console.log("Started upload image");
    console.log(imageUri);

    const formData = new FormData();

    const filename = imageUri.split('/').pop();

    const match = /\.(\w+)$/.exec(filename);
    const type = match ? `image/${match[1]}` : 'image/jpeg';

    formData.append('file', {
        uri: imageUri,
        name: filename,
        type: type,
    });

    try {
        const response = await axios.post(
            `${API_URL}/images/upload/${noticeId}`,
            formData,
            {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            }
        );
        console.info('Upload successful:', response.data);
        return response.data;
    } catch (error) {
        console.log("imageURI:", imageUri);
        console.error('Error uploading image:', error.response.data, error.response.status);
        throw error;
    }
}