package org.academiadecodigo.bootcamp11.sniperelite;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class SniperRifle {
    private int bulletDamage;
    private double crit;
    private double hit;
    private int shotsFired;
    private int shotsHit;

    public SniperRifle() {
        bulletDamage = 50;
        crit = 0.15;
        hit = 0.9;
        shotsFired = 0;
        shotsHit = 0;

        System.out.println("Sniper: I'm surrounded on all sides. Better get to work.\n");
    }

    public int getShotsFired() {
        return this.shotsFired;
    }

    public int getShotsHit() {
        return this.shotsHit;
    }

    public void shoot(Enemy enemy) {
        System.out.println("Sniper: \"" + enemy + " on my sights.\"");
        double damageVariation = bulletDamage/5;

        while (!enemy.isDead()) {
            shotsFired++;
            double damageRoll = Math.random() * damageVariation - damageVariation/2;
            int actualBulletDamage = (int) (this.bulletDamage + damageRoll);
            String shotOrCrit = "shot";
            if (Math.random() < crit) {
                actualBulletDamage *= 2;
                shotOrCrit = "crit";
            }

            System.out.println("-- Sniper " + shotOrCrit + " for " +
                               actualBulletDamage + " damage --");

            if (Math.random() < hit) {
                if (!enemy.hit(actualBulletDamage)) {
                    System.out.println("Sniper: \"Shot failed to connect.\"");
                } else {
                    System.out.println("Sniper: \"HOO HA\"");
                    this.shotsHit++;
                }
            } else {
                System.out.println("Sniper: \"Missed!\"");
            }
            System.out.println();
        }
        System.out.println("Sniper: \"One less nazi on the world.\"\n");
        System.out.println("-----------------------------------\n");
    }

    @Override
    public String toString() {
        StringBuilder message = new StringBuilder("=============================\n\n");
        String percentage = String.format("%d (%d%%)", this.shotsHit,
            Math.round((this.shotsHit/(double) this.shotsFired) * 100));

        message.append(String.format("Sniper Elite shot %d times\nand hit %s of them.",
            this.shotsFired, ((this.shotsHit==this.shotsFired) ? "all" : percentage)));
        message.append("\n\n=============================");
        return message.toString();
    }
}
