#include "defs.h"

void install_autodoc(void)
{
    player_t *p = &G->player;
    msg("You have found an AutoDoc");

    if (!display_prompt_yn("Go in (g), or ignore it (i)? "))
        return;

    msg("MediMech Industries, a subsidiary of MegaTech, thanks you for your patronage.");

    if (p->hp >= p->max_hp && !(p->status & ~0u)) {
        msg("How nice.  You are perfectly healthy and do not need that treatment.");
        msg("Have a nice day, Citizen.");
        return;
    }

    msg("Your request (w,h,s,c): ");
    int ch = wgetch(G->win_map);

    int cost = 0;
    switch (ch) {
    case 'w':  /* Wounds */
        cost = (p->max_hp - p->hp) * 5;
        if (cost <= 0) {
            msg("How nice.  You are perfectly healthy and do not need that treatment.");
            break;
        }
        if (p->savings < cost) {
            msg("You do not have sufficient funds for that request, and we do not give credit.");
            break;
        }
        p->savings -= cost;
        p->hp = p->max_hp;
        msg("There now, we trust you feel better Citizen.");
        break;

    case 'h':  /* Full health */
        cost = (p->max_hp - p->hp) * 5 + 100;
        if (p->savings < cost) {
            msg("You do not have sufficient funds for that request, and we do not give credit.");
            break;
        }
        p->savings -= cost;
        p->hp = p->max_hp;
        p->status = 0;
        for (int i = 0; i < 23; i++) p->status_timers[i] = 0;
        msg("We feel all better now, don't we Citizen?");
        break;

    case 's':  /* Status only */
        cost = 50;
        if (p->savings < cost) {
            msg("You do not have sufficient funds for that request, and we do not give credit.");
            break;
        }
        p->savings -= cost;
        p->status = 0;
        for (int i = 0; i < 23; i++) p->status_timers[i] = 0;
        msg("There now, we trust you feel better Citizen.");
        break;

    case 'c':  /* Cancel */
        break;

    default:
        msg("...clank...clatter...fizzle...");
        msg("... ZOT!");
        player_take_damage(rng(1, 4), "AutoDoc malfunction");
        break;
    }

    msg("A sound mind, and a sound body, makes a good Citizen!");
    msg("Have a nice day.");
}

void install_transmat(void)
{
    player_t *p = &G->player;
    msg("You have found a Transmat Booth");

    if (!display_prompt_yn("Go in (g), or ignore it (i)? "))
        return;

    char buf[16];
    char prompt[48];
    snprintf(prompt, sizeof(prompt), "Destination level (1-%d): ", G->n_levels + 1);
    msg("Your destination: ");
    if (display_prompt_str(prompt, buf, 4) <= 0) {
        msg("(cancelled)");
        return;
    }

    int dest = atoi(buf);
    if (dest < 1 || dest > G->n_levels + 1) {
        msg("We're sorry, but we do not currently service the destination you requested.");
        msg("We apologize for any inconvenience this may have caused you, Citizen.");
        return;
    }

    int cost = abs(dest - (G->cur_level + 1)) * 50;
    if (dest == G->cur_level + 1) {
        msg("How convenient, you are already at your destination!");
        return;
    }

    if (p->savings < cost) {
        msg("You do not have sufficient funds for that destination, Citizen ...");
        msg("... and we do not give credit");
        return;
    }

    p->savings -= cost;
    msg("...sizzle...crackle...sputter...");
    msg("ZZZZZZZZZZZZZZZZZZZAP!");

    G->cur_level = dest - 1;
    level_t *lev = map_get_level(G->cur_level);

    /* Place player on level */
    for (int y = 0; y < MAP_H; y++)
        for (int x = 0; x < MAP_W; x++)
            if (lev->map[y][x].tile == T_FLOOR) {
                p->x = x;
                p->y = y;
                goto placed_transmat;
            }
placed_transmat:
    p->depth = G->cur_level;
    p->region = 1 + G->cur_level / 10;

    msg("Service with a smile, Citizen!");
    msg("We trust it was a pleasant trip, Citizen.");
    msg("TransMech Corp, a subsidiary of MegaTech, thanks you for your patronage.");
    msg("Have a nice day.");
}

void install_vending(void)
{
    player_t *p = &G->player;
    msg("You have found a Vending Machine Stall");

    if (!display_prompt_yn("Go in (g), or ignore it (i)? "))
        return;

    msg("Your request (g,s,l,t,f): ");
    int ch = wgetch(G->win_map);

    struct { int type; int cost; } stock[] = {
        { IT_GYROJET, 10 },
        { IT_STALE_COOKIE, 5 },
        { IT_LIGHT_GLOBE, 25 },
        { IT_POWERCELL, 50 },
        { IT_NEEDLE, 15 },
    };
    int nstock = sizeof(stock) / sizeof(stock[0]);

    int idx = -1;
    switch (ch) {
    case 'g': idx = 0; break;
    case 's': idx = 1; break;
    case 'l': idx = 2; break;
    case 't': idx = 3; break;  /* Actually powercell */
    case 'f': idx = 4; break;
    default:
        msg("(cancelled)");
        return;
    }

    if (idx < 0 || idx >= nstock) return;

    if (p->savings < stock[idx].cost) {
        msg("You do not have sufficient funds for that request, and we do not give credit.");
        return;
    }

    if (p->inv_count >= MAX_INV) {
        msg("You are carrying all you can handle");
        return;
    }

    if (player_total_weight(p) + item_weight(stock[idx].type) > player_max_weight(p)) {
        msg("If you make that purchase, Citizen, you will not be able to carry it.");
        return;
    }

    p->savings -= stock[idx].cost;
    item_t newit = item_create(stock[idx].type);
    if (stock[idx].type == IT_LIGHT_GLOBE) {
        newit.charges = 500;
    }
    p->inventory[p->inv_count++] = newit;
    msg("Clatter ... clunk!");
    msg("It gives you %s", item_type_name(stock[idx].type));
    msg("(item %c.)", 'a' + p->inv_count - 1);
    msg("Service with a smile, Citizen");
    msg("InstaShop Ltd, a subsidiary of MegaTech, thanks you for your patronage.");
    msg("Have a nice day.");
}

void install_bank(void)
{
    player_t *p = &G->player;
    msg("You have found a Bank");

    if (!display_prompt_yn("Go in (g), or ignore it (i)? "))
        return;

    msg("Your transaction (d,w,b): ");
    int ch = wgetch(G->win_map);

    switch (ch) {
    case 'd': {  /* Deposit */
        char buf[16];
        msg("Amount to deposit: ");
        if (display_prompt_str("Amount: ", buf, 10) <= 0) break;
        int amt = atoi(buf);
        if (amt <= 0) { msg("Invalid amount specified"); break; }
        /* Find coins in inventory */
        int coins = 0;
        for (int i = 0; i < p->inv_count; i++) {
            if (p->inventory[i].type == IT_COIN)
                coins += p->inventory[i].qty;
        }
        if (coins < amt) {
            msg("You do not have sufficient funds for that deposit, and we do not give credit.");
            break;
        }
        /* Remove coins */
        int remaining = amt;
        for (int i = p->inv_count - 1; i >= 0 && remaining > 0; i--) {
            if (p->inventory[i].type == IT_COIN) {
                int take = remaining < p->inventory[i].qty ? remaining : p->inventory[i].qty;
                p->inventory[i].qty -= take;
                remaining -= take;
                if (p->inventory[i].qty <= 0) {
                    for (int j = i; j < p->inv_count - 1; j++)
                        p->inventory[j] = p->inventory[j + 1];
                    p->inv_count--;
                    if (p->wielded > i) p->wielded--;
                    if (p->reserve > i) p->reserve--;
                    if (p->worn_armor > i) p->worn_armor--;
                    if (p->worn_helmet > i) p->worn_helmet--;
                }
            }
        }
        p->savings += amt;
        msg("Your savings balance is now %d", p->savings);
        break;
    }

    case 'w': {  /* Withdraw */
        char buf[16];
        msg("Amount to withdraw: ");
        if (display_prompt_str("Amount: ", buf, 10) <= 0) break;
        int amt = atoi(buf);
        if (amt <= 0) { msg("Invalid amount specified"); break; }
        if (p->savings < amt) {
            msg("You do not have sufficient funds for that withdrawl, and we do not give credit.");
            break;
        }
        p->savings -= amt;
        /* Add coins to inventory */
        int found = -1;
        for (int i = 0; i < p->inv_count; i++) {
            if (p->inventory[i].type == IT_COIN) {
                found = i;
                break;
            }
        }
        if (found >= 0) {
            p->inventory[found].qty += amt;
        } else if (p->inv_count < MAX_INV) {
            item_t coin = item_create(IT_COIN);
            coin.qty = amt;
            p->inventory[p->inv_count++] = coin;
        }
        msg("Your savings balance is now %d", p->savings);
        break;
    }

    case 'b':  /* Balance */
        msg("Your savings balance is %d", p->savings);
        break;

    default:
        msg("(cancelled)");
        break;
    }

    msg("A penny saved is a penny earned, Citizen!");
    msg("Service with a smile, Citizen");
    msg("ReadiCash Ltd, a subsidiary of MegaTech, thanks you for your patronage.");
    msg("Have a nice day.");
}

void install_library(void)
{
    player_t *p = &G->player;
    msg("You have found a Library");

    if (!display_prompt_yn("Go in (g), or ignore it (i)? "))
        return;

    if (rng_chance(20)) {
        msg("It does not appear to be operational");
        return;
    }

    msg("Selected item: ");
    int slot = display_prompt_item("Identify");
    if (slot < 0) return;

    int cost = 25;
    if (p->savings < cost) {
        msg("We are sorry, Citizen, but you do not have sufficient funds to cover that");
        msg("request, and we do not offer credit.");
        return;
    }

    p->savings -= cost;
    item_t *it = &p->inventory[slot];
    it->is_identified = 1;

    if (it->type == IT_PILL) {
        G->pill_names_known[it->pill_type] = 1;
        msg("Identification:  pill of %s",
            it->pill_type < PILL_COUNT ?
            (const char *[]) {
                "death", "poison", "enhance Strength", "deplete Strength",
                "invigoration", "debilitation", "manual dexterity", "ineptitude",
                "glamor", "beastliness", "cleverness", "dimwittedness",
                "acumen", "stupidity", "keen sightedness", "blindness",
                "speed", "clumsiness", "dizziness", "cure blindness",
                "cure clumsiness", "cure dizziness", "neutralize poison",
                "good health", "improved hearing", "perception", "antagonism",
                "sleep", "disorientation", "cure confusion", "slowness",
                "flying", "healing", "learning", "regression",
                "forgetfulness", "memory loss", "unknown properties", "unknown properties"
            }[it->pill_type] : "unknown properties");
    } else {
        msg("Identification:  %s", item_type_name(it->type));
    }

    msg("Service with a smile, Citizen");
    msg("Diversified MicroData, a subsidiary of MegaTech, thanks you for your patronage.");
    msg("Have a nice day.");
}

void install_factory(void)
{
    player_t *p = &G->player;
    msg("You have found the MegaTech Factory Outlet");

    if (!display_prompt_yn("Go in (g), or ignore it (i)? "))
        return;

    if (rng_chance(10)) {
        msg("Sorry, it appears to be closed ...");
        msg("... a prominent sign reads:  \"Temporarily out of service\"");
        return;
    }

    /* Show available items */
    struct { int type; int cost; } stock[] = {
        { IT_COMBAT_KNIFE, 50 },
        { IT_GYROJET_PISTOL, 200 },
        { IT_LASER_PISTOL, 350 },
        { IT_LEATHER_JACKET, 100 },
        { IT_KEVLAR_JACKET, 300 },
        { IT_LIGHT_GLOBE, 25 },
        { IT_POWERCELL, 50 },
        { IT_GAS_MASK, 75 },
        { IT_GYROJET, 10 },
        { IT_GRENADE, 100 },
    };
    int nstock = sizeof(stock) / sizeof(stock[0]);

    for (int i = 0; i < nstock; i++) {
        msg(" %c. %-19.19s %6d", 'a' + i, item_type_name(stock[i].type), stock[i].cost);
    }

    msg("Purchase (item or CANCEL) ");
    int ch = wgetch(G->win_map);
    int idx = -1;
    if (ch >= 'a' && ch < 'a' + nstock) idx = ch - 'a';

    if (idx < 0) {
        msg("(cancelled)");
    } else {
        if (p->savings < stock[idx].cost) {
            msg("Sorry Citizen, you cannot afford that request and we do not offer credit");
        } else if (p->inv_count >= MAX_INV) {
            msg("You are carrying all you can handle");
        } else if (player_total_weight(p) + item_weight(stock[idx].type) > player_max_weight(p)) {
            msg("If you make that purchase, Citizen, you will not be able to carry it.");
        } else {
            p->savings -= stock[idx].cost;
            item_t newit = item_create(stock[idx].type);
            if (stock[idx].type == IT_LIGHT_GLOBE)
                newit.charges = 500;
            if (stock[idx].type == IT_GYROJET_PISTOL || stock[idx].type == IT_LASER_PISTOL)
                newit.ammo = 10;
            p->inventory[p->inv_count++] = newit;
            msg("(item %c.)", 'a' + p->inv_count - 1);
            msg("Your savings balance is now %d", p->savings);
        }
    }

    msg("Service with a smile, Citizen");
    msg("MegaTech International thanks you for your patronage.");
    msg("Have a nice day.");
}

void install_reclamation(void)
{
    player_t *p = &G->player;
    msg("You have found the Reclamation Center");

    if (!display_prompt_yn("Go in (g), or ignore it (i)? "))
        return;

    if (rng_chance(10)) {
        msg("Sorry, it appears to be closed ...");
        msg("... a prominent sign reads:  \"Temporarily out of service\"");
        return;
    }

    msg("Dump");
    int slot = display_prompt_item("Reclaim");
    if (slot < 0) return;

    item_t *it = &p->inventory[slot];
    int value = it->value > 0 ? it->value / 2 : rng(1, 10);

    if (it->type == IT_CORPSE || it->type == IT_ENTRAILS || it->type == IT_SCRAPMETAL ||
        it->type == IT_BONE || it->type == IT_SKULL || it->type == IT_EMPTY_BEER_CAN ||
        it->type == IT_BROKEN_BOTTLE || it->type == IT_DIRTY_RAG ||
        it->type == IT_PILE_OF_RUBBLE || it->type == IT_BOTTLE_TOP ||
        it->type == IT_MILK_CARTON || it->type == IT_DEAD_POWERCELL ||
        it->type == IT_LARGE_DEAD_POWERCELL || it->type == IT_TRASH_CAN_LID) {

        if (slot == p->wielded) { p->wielded = -1; p->wc = 0; }
        if (slot == p->reserve) p->reserve = -1;
        if (slot == p->worn_armor) { p->worn_armor = -1; p->ac = 0; }
        if (slot == p->worn_helmet) p->worn_helmet = -1;

        for (int i = slot; i < p->inv_count - 1; i++)
            p->inventory[i] = p->inventory[i + 1];
        p->inv_count--;
        if (p->wielded > slot) p->wielded--;
        if (p->reserve > slot) p->reserve--;
        if (p->worn_armor > slot) p->worn_armor--;
        if (p->worn_helmet > slot) p->worn_helmet--;

        p->savings += value;
        msg("Your savings account has increased by %d credits", value);
        msg("Thank you, Citizen");
    } else {
        msg("We're sorry citizen, but we do not accept such items for reclamation purposes.");
    }

    msg("A clean city makes for happy Citizens!");
    msg("Service with a smile, Citizen");
    msg("Nif-Tee-Junk, a MegaTech subsidiary, thanks you for your patronage.");
    msg("Have a nice day.");
}

void install_fountain(void)
{
    msg("You have found a water fountain");

    if (!display_prompt_yn("Take a drink (d), or ignore it (i)? "))
        return;

    if (rng_chance(10)) {
        msg("The water dribbles out onto the floor");
        return;
    }
    if (rng_chance(5)) {
        msg("It seems to be out of water");
        return;
    }

    msg("Glug glug glug!");
    msg("Slurp!");
    msg("Tastes clean and refreshing ...");
    player_heal(rng(2, 8));

    if (player_has_status(SF_DIZZY)) {
        player_remove_status(SF_DIZZY);
        msg("You no longer feel dizzy");
    }
    if (player_has_status(SF_CONFUSED)) {
        player_remove_status(SF_CONFUSED);
        msg("You no longer feel confused");
    }
    if (player_has_status(SF_VULNERABLE)) {
        player_remove_status(SF_VULNERABLE);
        msg("You no longer feel vulnerable");
    }
}

void install_generator(void)
{
    player_t *p = &G->player;
    msg("You have found a generator");

    if (!display_prompt_yn("Use it (u), or ignore it (i)? "))
        return;

    if (rng_chance(20)) {
        msg("You fumble with it for a moment, but nothing seems to happen ...");
        return;
    }

    msg("Recharge (item) ");
    int slot = display_prompt_item("Recharge");
    if (slot < 0) return;

    item_t *it = &p->inventory[slot];
    if (it->charges >= 100) {
        msg("It is already fully charged");
        return;
    }

    if (rng_chance(15)) {
        msg("ZZZZZZZZZZZZZZORCH!");
        player_take_damage(rng(3, 10), "generator overload");
    } else {
        it->charges = 100;
        msg("Zzzzzzzt!");
    }
}

void install_stargate(void)
{
    player_t *p = &G->player;

    if (p->mission == MISSION_2_ACTIVE && p->queen_dead) {
        msg("You have found a StarGate");
        msg("Scintillating veils of light suddenly appear and englobe you as ...");
        msg("... a great throbbing sound begins to resonate from the StarGate ...");

        /* Check for spacesuit */
        int has_suit = 0;
        for (int i = 0; i < p->inv_count; i++) {
            if (p->inventory[i].type == IT_SPACESUIT && p->inventory[i].is_active) {
                has_suit = 1;
                break;
            }
        }
        if (!has_suit) {
            msg("... but before much else can happen you succumb to oxygen starvation ...");
            msg("... as the remaining air escapes from your damaged spacesuit ...");
            player_take_damage(999, "suffocated");
            return;
        }

        msg("... and after a few moments there is a sudden crackle of energy ...");
        p->mission = MISSION_2_COMPLETE;
        p->bonus_pts += 10000;
    } else {
        msg("You have found a very large unknown device");
        if (!display_prompt_yn("Use it (u), or ignore it (i)? "))
            return;
        msg("Nothing seems to happen");
    }
}
