package com.bitdecay.game.system;

import com.badlogic.gdx.physics.box2d.*;
import com.bitdecay.game.component.DamageComponent;
import com.bitdecay.game.component.DrawableComponent;
import com.bitdecay.game.component.HealthComponent;
import com.bitdecay.game.gameobject.MyGameObject;
import com.bitdecay.game.room.AbstractRoom;
import com.bitdecay.game.system.abstracted.AbstractSystem;
import com.bitdecay.game.util.ContactDistributer;

/**
 * Created by Luke on 4/22/2017.
 */
public class HealthSystem extends AbstractSystem implements ContactListener {

    public HealthSystem(AbstractRoom room, ContactDistributer contactDistrib) {
        super(room);
        contactDistrib.listeners.add(this);
    }

    @Override
    protected boolean validateGob(MyGameObject gob) {
        return false;
    }

    @Override
    public void beginContact(Contact contact) {
        MyGameObject objectA = (MyGameObject) contact.getFixtureA().getBody().getUserData();
        MyGameObject objectB = (MyGameObject) contact.getFixtureB().getBody().getUserData();
        if(objectA != null && objectB != null){
            applyDamage(objectA, objectB);
            applyDamage(objectB, objectA);


            //for testing only
//            objectA.forEachComponentDo(HealthComponent.class, health -> System.out.println(health.currentHealth));
//            objectB.forEachComponentDo(HealthComponent.class, health -> System.out.println(health.currentHealth));
        }
    }

    @Override
    public void endContact(Contact contact) {

    }

    @Override
    public void preSolve(Contact contact, Manifold manifold) {

    }

    @Override
    public void postSolve(Contact contact, ContactImpulse contactImpulse) {

    }

    public void applyDamage(MyGameObject attacker, MyGameObject attacked){
        attacker.forEach(DamageComponent.class, dmg -> attacked.forEach(HealthComponent.class, health ->{
            log.info("Health " + health.currentHealth + "/" + health.maxHealth + " - " + dmg.damage);
            health.set(health.currentHealth - dmg.damage);

            attacked.forEachComponentDo(DrawableComponent.class, drawable -> {
                float grey = (float) health.currentHealth / ((float) health.maxHealth * 0.8f);
                drawable.color.set(grey, grey, grey, 1);
            });
        }));

    }
}

@@ -1997,19 +1997,66 @@
 g.damage
+ + %22 == %22 + (health.currentHealth - dmg.damage)
 );%0A
-
         
@@ -2186,16 +2186,50 @@
 le -%3E %7B%0A
+                float min = 0.3f;%0A
         
@@ -2249,16 +2249,18 @@
  grey = 
+((
 (float) 
@@ -2282,17 +2282,16 @@
 ealth / 
-(
 (float) 
@@ -2310,15 +2310,70 @@
 alth
+)
  * 
-0.8f
+(1 - min)) + min;%0A                log.info(%22Grey: %22 + grey
 );%0A 

move min tint to .3