import { anthill } from "./anthill.js";
import { Signalant } from "./signalant.js";
import { storage } from "./storage.js";
import { tutorial } from "./tutorial.js";

let nextShopSignalantId = 1;

function createShopSignalant() {
    return new Signalant(`shop_signalant_${nextShopSignalantId++}`, {
        toStorage: true,
        direction: Math.random() * 360,
        isFixed: false,
        isActive: false
    });
}

export class Shop {
    constructor() {
        this.offerCount = 3;
        this.signalantOffers = [];
    }

    canGenerateOffers() {
        return anthill.unlockedAntsData.length > 0 && anthill.canAccessSignalants();
    }

    ensureSignalantOffers() {
        if (this.signalantOffers.length === this.offerCount || !this.canGenerateOffers()) {
            return this.signalantOffers;
        }

        this.rerollSignalantOffers();
        return this.signalantOffers;
    }

    rerollSignalantOffers() {
        if (!this.canGenerateOffers()) {
            this.signalantOffers = [];
            return this.signalantOffers;
        }

        this.signalantOffers = Array.from({ length: this.offerCount }, () => createShopSignalant());
        return this.signalantOffers;
    }

    getSignalantOffers() {
        return this.ensureSignalantOffers();
    }

    getSignalantOffer(index) {
        const offers = this.ensureSignalantOffers();
        if (index < 0 || index >= offers.length) {
            return null;
        }

        return offers[index] || null;
    }

    buySignalantOffer(index) {
        if (!anthill.canAccessSignalants()) {
            return false;
        }

        const offer = this.getSignalantOffer(index);
        if (!offer) {
            return false;
        }

        if (!anthill.spendPurchaseCost(anthill.getSignalantPurchaseKey())) {
            return false;
        }

        storage.addSignalant(offer);
        this.rerollSignalantOffers();
        tutorial.trigger("signalant.buy");
        return true;
    }
}

export const shop = new Shop();