import axios from 'axios';

const BUSCAMAN_URL = 'https://gps.buscalia.com/usuario/localizar.aspx?bmi=true&addr=';

export async function openBuscaman(vehicleId, tickets) {
    if (!vehicleId) throw new Error(`The route doesn't have a vehicle`);

    const response = await axios.get(`Routes/${vehicleId}/getDeliveryPoint`);

    if (!response.data) {
        throw new Error(`The route's vehicle doesn't have a delivery point`);
    }

    let addresses = response.data;
    tickets.forEach((ticket, index) => {
        const previousLine = tickets[index - 1] ? tickets[index - 1].street : null;
        if (previousLine !== tickets.street) {
            addresses += `+to:${ticket.postalCode} ${ticket.city} ${ticket.street}`;
        }
    });
    window.open(BUSCAMAN_URL + encodeURI(addresses), '_blank');
}
