aboutsummaryrefslogtreecommitdiff
path: root/src/buy.c
blob: fbe98ca5d7b33e76d55f887159a43415fabc157f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "globals.h"

void buy_handler(struct player_t *player)
{
    output("Enter the ticker symbol of the stock you wish to purchase: ");
    char *sym = read_ticker();

    struct money_t price;

    output("Getting stock information...\n");

    char *name;

    if(!get_stock_info(sym, &price, &name))
    {
        output("Failed to get query information for '%s'.\n", sym);
        free(sym);
        return;
    }

    output("Stock name: %s\n", name);
    output("Price per share: $%llu.%02llu\n",
           price.cents / 100, price.cents % 100);
    output("Enter the number of shares to be purchased (maximum %llu): ",
           player->cash.cents / price.cents);

    ullong count = read_int();

    if(count <= 0)
    {
        output("Purchase cancelled.\n");
        return;
    }

    ullong cost = price.cents * count;

    if(cost > player->cash.cents)
    {
        output("Not enough money!\n");
        return;
    }

    output("This will cost $%llu.%02llu. Are you sure? ",
           cost / 100, cost % 100);
    char *response = read_string();
    all_lower(response);

    if(response[0] == 'y')
    {
        output("Confirmed.\n");

        struct stock_t *stock = find_stock(player, sym);

        /* add the stock to the portfolio or increase the count of a stock */

        if(stock)
        {
            stock->count += count;
            stock->current_price.cents = price.cents;
        }
        else
        {
            /* stock is not in portfolio yet, add it */

            player->portfolio_len += 1;
            player->portfolio = realloc(player->portfolio,
                                        player->portfolio_len * sizeof(struct stock_t));
            player->need_to_free_portfolio = true;

            stock = player->portfolio + player->portfolio_len - 1;

            memset(stock, 0, sizeof(struct stock_t));

            stock->symbol = sym;
            stock->fullname = name;
            stock->count = count;
            stock->current_price.cents = price.cents;
        }

        player->cash.cents -= cost;

        add_hist(stock, BUY, count);

        /* sort the portfolio alphabetically by ticker symbol */
        qsort(player->portfolio,
              player->portfolio_len, sizeof(struct stock_t),
              compare_stocks);
    }
    else
    {
        output("Not confirmed.\n");
    }

    free(response);
}