package leigh.minecraft.leighco.cmd;

import leigh.mecha.cli.CommandHandler;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.minecraft.leighco.LeighCoState;
import leigh.minecraft.leighco.Lot;
import leigh.minecraft.MarblesUtil;

/**
 * Implementation of the /LC BUY LAND command. The purpose of this command is to facilitate player purchases of
 * real-estate.
 * <p>
 * Limitations: Currently the command only supports buying land from the server (vs. private-party sales, which may
 * be supported at a future date).
 */
public class LandBuyCommand implements CommandHandler<LeighCoState> {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(LandBuyCommand.class);

    private final int landPrice = 19;

    @Override
    public void handle(String[] cmd, LeighCoState state) throws Exception {
        if ((cmd.length != 2 && cmd.length != 3) || !cmd[1].equals("16") &&
                !cmd[1].equals("32") &&
                !cmd[1].equals("64") &&
                !cmd[1].equals("128") &&
                !cmd[1].equals("256") &&
                !cmd[1].equals("512") &&
                !cmd[1].equals("1024")) {
            state.sendMessage("Usage: /lc land buy 16|32|64|128|256|512|1024");
            return;
        }

        // We previously guaranteed this will work
        int sz = Integer.parseInt(cmd[1]);
        int price = (sz * sz) * landPrice;
        Lot lot = new Lot(state.getLocation(), sz);

        logger.info("Calculated lot. {} from position {}", lot, state.getLocation());
        String lotSb = "Area: " +
                lot.getX1() +
                "," +
                lot.getZ1() +
                " -> " +
                lot.getX2() +
                "," +
                lot.getZ2();

        state.sendMessage("Area: " + lotSb);
        state.sendMessage("Price: " + MarblesUtil.formatCents(price));

        if (cmd.length == 2) {
            String sb = "To confirm price, enter /lc land buy " + sz + " confirm";
            state.sendMessage(sb);
        } else {
            if (cmd[2].equals("confirm")) {
                // We do not need to reply - landCreate() will pass on the returned message to the caller
                state.getApp().landCreate(lot, state.getPlayerName(), price);
            } else {
                state.sendMessage("Land purchase not confirmed.");
            }
        }
    }
}
