//=============================================================================
// * Get Status Face Index
//Here is where we set up the portrait used for when plot armor is activated.
//Change the "20" in LINE 16 of this plugin, and replace it with the number of your actor's ID.
//The "return 3" is the row of the spritesheet that the portrait is located, with "3" being the number
//of the row, change the "3" to another number if you want to use another row.
//You can also assign portraits for multiple characters, simply copy LINE 16 and paste it right below,
//then repeat the process.
//Like this example:
// if(!!$gameTemp._secondChance && this.actorId() === 20) {return 3;}
// if(!!$gameTemp._secondChance && this.actorId() === 21) {return 3;}
//=============================================================================
{
  Game_Actor.prototype.statusFaceIndex = function () {
  if(!!$gameTemp._secondChance && this.actorId() === 1) {return 3;}
  if(!!$gameTemp._secondChance && this.actorId() === 20) {return 3;}
  if(!!$gameTemp._damagedPlayer) {return 2;}
  // If Use victory face and is alive
  if (this._useVictoryFace && this.isAlive()) {
    // Return victory face
    return 10;
  };
  // Check for second Chance;
  // Get Main State
  var state = this.states().find(st => st.meta.StateFaceIndex);
  // If State
  if (state) {
    // If Alt switch index exist
    if (state.meta.AltIndexSwitch) {
      // If alt switch is on
      if ($gameSwitches.value(Number(state.meta.AltIndexSwitch))) {
        // Return alternate face index
        return Number(state.meta.AltStateFaceIndex)
      };
    }
    // If face index exists return it
    //if(state.id === this.deathStateId() && this.actorId() === 1) {return 9;}
    if (state.meta.StateFaceIndex) { return Number(state.meta.StateFaceIndex); };
  };
  // Get Fear Index
  const fearIndex = this.actor().meta.FearBattleFaceIndex;
  // If Fear index is valid and switch 92 is on
  if (fearIndex && $gameSwitches.value(92)) {
    return Number(fearIndex)
  }
  // Return default
  return 0;
  };
}


//=============================================================================
// * Get Status Back Index
//Here is where we set up the background used for when plot armor is activated.
//Change the "20" in LINE 68 of this plugin, and replace it with the number of your actor's ID.
//The "return 11" is the index of the background in the file "faceset_states" in the image folder. 
//Index 11 is the afraid background, change the "11" to another number if you want to use another background.
//You can also assign backgrounds for multiple characters, simply copy LINE 68 and paste it right below,
//then repeat the process.
//Like this example:
// if(!!$gameTemp._secondChance && this.actorId() === 20) {return 11;}
// if(!!$gameTemp._secondChance && this.actorId() === 21) {return 11;}
//=============================================================================
{
  Game_Actor.prototype.statusBackIndex = function () {
  // Omori
  if($gameTemp._secondChance && this.actorId() === 1) {return 11;}
  if($gameTemp._secondChance && this.actorId() === 20) {return 11;}
  // Get Main State
  var state = this.states().find(st => st.meta.StateBackIndex);
  // If State
  if (state && state.meta.StateBackIndex) {
    return Number(state.meta.StateBackIndex);
  };
  // Return default
  return 0;
  };
}


//=============================================================================
// * Update Damage
//This changes the hurt sprite turn into the plot armor sprite until the turn ends.
//Change the "20" in LINE 110 of this plugin, and replace it with the number of your actor's ID.
//You can add more characters to it by adding another   "&& actor.actorId() !== id"
//Like this:
//if(!$gameTemp._secondChance || actor.actorId() !== 1 && actor.actorId() !== 20  && actor.actorId() !== 21  ) {this._faceSprite.setAnimRow(9)}
//=============================================================================
{
  Window_OmoriBattleActorStatus.prototype.updateDamage = function() {
  // Get Actor
  var actor = this.actor();
  // If Actor Exists
  if (actor) {
    if (actor.isDamagePopupRequested()) {
      // Create Damage sprite
      var damage = new Sprite_Damage();
      damage.x = this.width / 2;
      damage.y = this.height - (40 + (20 * Math.floor(actor._damagePopup.length / 3))) + (40 * this._popupCount);
      damage.x += this._homePosition.x;
      damage.y += this._homePosition.y + 2;
      damage.setup(actor);
      // Get Result
      var result = actor._damagePopup[0] || actor.result();
      this._damageContainer.addChild(damage);
      this._damageSprites.push(damage);
      // If Damage is more than 0
      if (result.hpDamage > 0) {
        // Set Damage Face Animation
        if(!$gameTemp._secondChance || actor.actorId() !== 1 && actor.actorId() !== 20 ) {this._faceSprite.setAnimRow(9)}
      };
      this._popupCount++;
      // Clear Results
      //actor.clearDamagePopup();
      //actor.clearResult();
    }
    else {
      if(this._popupCount > 0) {this._popupCount = 0;}
    }
  };

  // Go Through Damage Sprites
  for (var i = 0; i < this._damageSprites.length; i++) {
    // Get Sprite
    var sprite = this._damageSprites[i];
    // If Damage is not playing anymore
    if (!sprite.isPlaying()) { this._removeDamageSprites.push(sprite); };
  };
  // If Removed Damage Sprites length is more than 0
  if (this._removeDamageSprites.length > 0) {
    // Go Through Removed Damage Sprites
    for (var i = 0; i < this._removeDamageSprites.length; i++) {
      // Get Sprite
      var sprite = this._removeDamageSprites[i];
      // Get Index
      var index = this._damageSprites.indexOf(sprite);
      // If Index exist
      if (index >= 0) { this._damageSprites.splice(index, 1); };
      // Remove Sprite
      this._damageContainer.removeChild(sprite);
    };
    // Clear Remove Damage sprites
    this._removeDamageSprites = [];
    };
  };
}

//=============================================================================
// * Second Chance Message
//This manages the message that appears when plot armor is activated.
//Change the "20" in LINES 179, 199 and 200 of this plugin, and replace it with the number of your actor's ID.
//replace "xx_newplotarmortext" with yaml you'll use. Keep in mind it has to match the yaml you use in troop 0.
//You can add more messages for other make characters by adding more "else if" statements.
//and putting the ids in the "$.Force_Clear_Plot_Armor" list below
//=============================================================================

(function($) {
	$.Process_Second_Chance_Message = function(target) {
		//if(target.actorId() !== 1) {return;} // If it's not OMORI do not process; yeah right bitch stfu
		if(!!$gameSwitches.value(1613)) { // PLOT ARMOR MESSAGE and FORCE PLOT ARMOR ?
			$gameSwitches.setValue(1613, false); // Plot Armor Message;
			$gameTemp._secondChance = true; // Activating second chance face;
			$gameSwitches.setValue(2000, true); // Preparing Plot Armor Battle Event Switch;
			SceneManager._scene._statusWindow.refresh();
			let Bubble_Toggle = $gameSwitches.value(6);
			if(target.actorId() == 1) {
				if(!!Bubble_Toggle) {
					$gameTemp._addToFinishActions = [
						["EVAL", [`$gameSwitches.setValue(6, false)`]],
						["EVAL", [`$gameMessage.showLanguageMessage("xx_battle_text.message_1000")`]],
						["EVAL", [`$gameSwitches.setValue(6, true)`]]
					]
				}
				else {
					$gameTemp._addToFinishActions = [
						["EVAL", [`$gameMessage.showLanguageMessage("xx_battle_text.message_1000")`]]
					]
				}
			} else if(target.actorId() == 20) {
				if(!!Bubble_Toggle) {
					$gameTemp._addToFinishActions = [
						["EVAL", [`$gameSwitches.setValue(6, false)`]],
						["EVAL", [`$gameMessage.showLanguageMessage("xx_newplotarmortext.message_0")`]],
						["EVAL", [`$gameSwitches.setValue(6, true)`]]
					]
				}
				else {
					$gameTemp._addToFinishActions = [
						["EVAL", [`$gameMessage.showLanguageMessage("xx_newplotarmrotext.message_0")`]]
					]
				}
			}
		}
	}

	$.Force_Clear_Plot_Armor = function() {
		$gameActors.actor(1).removeState(299); // First Hit;
		$gameActors.actor(1).removeState(300); // Plot Armor;
		$gameActors.actor(20).removeState(299); // First Hit;
		$gameActors.actor(20).removeState(300); // Plot Armor;
		$gameTemp._secondChance = false;
	}
})(Gamefall.OmoriFixes);
