<?php
/* Examples:
lootmob.php "((@m:=14294) IN (modelid_1,modelid_2) OR @m IN (SELECT modelid_other_gender FROM creature_model_info WHERE modelid=modelid_1) OR @m IN (SELECT modelid_other_gender FROM creature_model_info WHERE modelid=modelid_2))"
lootmob.php :world_ytdb "11447,11497,11498"
lootmob.php "(type=1 AND family=24 AND minlevel<=60 AND maxlevel>=60)"
lootmob.php #4770
lootmob.php #Thrall
*/
require "_trinity.php";

MySTART( DBnameFromArgv() );

if (substr($argv[1], 0, 1) == '#') { // смотреть по guid в таблице конкретных существ
   $argv[1] = substr($argv[1], 1);
   $argv[1] = intval($argv[1]) > 0 ? "(entry IN (SELECT id FROM creature WHERE guid=$argv[1]))" : "(name=\"$argv[1]\")";
}

$verbose = false;
if  ($creature_linking_TABLE = MyVAL("SHOW TABLES LIKE 'creature_linking'")) {}
else $creature_linking_TABLE = MyVAL("SHOW TABLES LIKE 'linked_respawn'");

$JoinGuidPool = "";
if (@$argv[count($argv)-1] == "/")  {
   $verbose = true; array_splice($argv,-1);
   if (mysql_query("SELECT guid, chance FROM pool_creature LIMIT 1"))
      $JoinGuidPool = "LEFT JOIN pool_creature USING(guid)";
}

$cname = "(rank=3)";
$res_crea = MyOP("SELECT * FROM creature_template WHERE ".EntryConditionFromArgv($cname)." ORDER BY MinLevel ASC,rank ASC,name ASC");
$ncreas = 0;
$global_refloots = 0;


while($crea = mysql_fetch_object($res_crea)) { // цикл по существам

if ($ncreas++ > 0)  echo "\n";

printf("%5s  %-14s %-40s %sc",
  $crea->entry,
  ($crea->minlevel == $crea->maxlevel ? "L$crea->minlevel" : "L$crea->minlevel..$crea->maxlevel")
  . " ". (isset($crea->HealthModifier) ? "*$crea->HealthModifier" :
         (isset($crea->Health_mod) ? "*$crea->Health_mod" :
         ($crea->minhealth == $crea->maxhealth ? $crea->maxhealth :
          "$crea->minhealth..$crea->maxhealth"
         )))
  . " ". (isset($crea->DamageModifier) ? "*$crea->DamageModifier" :
          round(($crea->mindmg + $crea->maxdmg)/2 * (isset($crea->dmg_multiplier) ? $crea->dmg_multiplier : 1)). "/".sprintf("%.1f", $crea->baseattacktime/1000)
         ),
  $crea->name,
  $crea->mingold == $crea->maxgold ? $crea->maxgold : "$crea->mingold-$crea->maxgold"
);

if (isset($crea->MechanicImmuneMask)) // Nostalrius DB
    { $crea->mechanic_immune_mask = $crea->MechanicImmuneMask; unset($crea->MechanicImmuneMask); }

if (!isset($crea->mechanic_immune_mask)) {
    echo "\n";
} elseif ($crea->mechanic_immune_mask == 0) {
    echo "  NO immunities\n";
} elseif (($crea->mechanic_immune_mask & 0x26EB7FFF) == 0x26EB7FFF) {
    echo "  ALL Immunities\n";
} elseif (substr_count(decbin($crea->mechanic_immune_mask & 0xFFFFF), "1") > 7) {
    echo "\n ", rdbits(0x26EB7FFF & ~intval($crea->mechanic_immune_mask), $bits_immunity), " <== MISSING\n";
} else {
    echo "\n ", rdbits($crea->mechanic_immune_mask, $bits_immunity), "\n";
}

if (/*strtolower($crea->name) == strtolower($cname)*/ $ncreas <= 100) {
    $res = MyOP( ($creature_linking_TABLE ?
      "SELECT * FROM creature LEFT JOIN $creature_linking_TABLE USING(guid) $JoinGuidPool" : "SELECT * FROM creature $JoinGuidPool"
     ). " WHERE id=$crea->entry ORDER BY map, position_x, position_y, position_z"
    );
    $prevmap = -1;
    $nguids = 0;
    while($r = mysql_fetch_object($res)) {
      if ($r->map != $prevmap) {
          if ($prevmap >= 0) echo ";  ";
          if (($map = @$wowmaps[$r->map]) == "")  $map = "??? ($r->map):";
          echo "  $map ($r->map):";
          $prevmap = $r->map;
      }
      if ($verbose) {
         printf("\n%10s %s%7s  %9.2f %9.2f %9.2f %d  %d:%.2f", "#".$r->guid,
            isset($r->modelid) ? sprintf("%5d ",$r->modelid) : "",
            isset($r->spawntimesecsmin) ? # Nostalrius
              $r->spawntimesecsmin.($r->spawntimesecsmin!=$r->spawntimesecsmax ? "..".$r->spawntimesecsmax : "")."s"
              : $r->spawntimesecs."s",
            $r->position_x, $r->position_y, $r->position_z, $r->map, $r->MovementType, $r->spawndist
         );
         if (isset($r->chance))
             printf("  *%s:%s%s", $r->pool_entry, $r->chance, ""/*@$r->description == "" ? "":" $r->description"*/);
         if (isset($r->master_guid))
             printf("  -> #%d (%d)", $r->master_guid, $r->flag);
         if (isset($r->linkedGuid))
             printf("  -> #%d (%d)", $r->linkedGuid, $r->linkType);

      } else
         echo " ($r->position_x $r->position_y $r->position_z)";
      ++$nguids;
    }
    if ($prevmap >= 0)  echo " {",$nguids,"}\n";
}


if ($verbose) {
    ViewRelatedData($crea, &$requestPCT, array(
      "SELECT * FROM pool_creature_template WHERE id="),
      "",
      "Cannot access `pool_creature_template` table in this DB",
      "Not defined in `pool_creature_template`",
      "from `pool_creature_template`"
    );

    /* эти данные уже были в списке конкретных экземпляров
    ViewRelatedData($crea, &$requestPC, array(
      "SELECT pc.* FROM pool_creature AS pc JOIN creature USING(guid) JOIN creature_template ON id=entry WHERE entry="),
      "",
      "Cannot access `pool_creature` table in this DB",
      "Not defined in `pool_creature`",
      "from `pool_creature`"
    );
    */

    ViewRelatedData($crea, &$requestCLT, array(
      "SELECT * FROM creature_linking_template WHERE entry="),
      "",
      "Cannot access `creature_linking_template` table in this DB",
      "Not defined in `creature_linking_template`",
      "from `creature_linking_template`"
    );

    /* эти данные уже были в списке конкретных экземпляров
    ViewRelatedData($crea, &$requestCL, array(
      "SELECT cl.* FROM $creature_linking_TABLE AS cl JOIN creature USING(guid) JOIN creature_template ON id=entry WHERE entry="),
      "",
      "Cannot access `$creature_linking_TABLE` in this DB",
      "Not defined in `$creature_linking_TABLE`",
      "from `$creature_linking_TABLE`"
    );
    */

    ViewRelatedData($crea, &$requestCOR, array(
      "SELECT * FROM creature_onkill_reputation WHERE creature_id="),
      "",
      "Cannot access `creature_onkill_reputation` table in this DB",
      "Not defined in `creature_onkill_reputation`",
      "from `creature_onkill_reputation`"
    );

    ViewRelatedData($crea, &$requestEC, array(
      "SELECT gec.* FROM game_event_creature AS gec JOIN creature USING(guid) JOIN creature_template ON id=entry WHERE entry="),
      "",
      "Cannot access `game_event_creature` table in this DB",
      "Not defined in `game_event_creature`",
      "from `game_event_creature`"
    );

    ViewRelatedData($crea, &$requestAI, array(
      "SELECT * FROM creature_ai_scripts WHERE creature_id=",
      "SELECT * FROM creature_ai_scripts WHERE entryOrGUID=" /* HGDB */,
      "SELECT * FROM smart_scripts WHERE entryOrGUID=" /* TrinityCore, SunwellCore */),
      " ORDER BY id", 
      "Cannot access `creature_ai_scripts` or `smart_scripts` table in this DB",
      "Not defined in EventAI table",
      ""
    );

    ViewRelatedData($crea, &$requestCMT, array(
      "SELECT GROUP_CONCAT(DISTINCT cm.id SEPARATOR ', ') FROM creature_movement AS cm JOIN creature AS c ON cm.id=c.guid JOIN creature_template AS ct ON ct.entry=c.id WHERE ct.entry=",
      "SELECT GROUP_CONCAT(DISTINCT cm.id SEPARATOR ', ') FROM waypoint_data     AS cm JOIN creature AS c ON FLOOR(cm.id/10)=c.guid JOIN creature_template AS ct ON ct.entry=c.id WHERE ct.entry=" /* TrinityCore, SunwellCore */),
      " ORDER BY cm.id", 
      "Cannot access `creature_movement` or `waypoint_data` table in this DB",
      "Not defined in `creature_movement` or `waypoint_data` table",
      "guids in `creature_movement` or `waypoint_data`"
    );

    ViewRelatedData($crea, &$requestAdT, array(
      "SELECT * FROM creature_template_addon WHERE entry="),
      "",
      "Cannot access `creature_template_addon` table in this DB",
      "Not defined in `creature_template_addon`",
      "from `creature_template_addon`"
    );

    ViewRelatedData($crea, &$requestCMI, array(
      "SELECT cmi.* FROM creature_model_info AS cmi JOIN creature_template ON modelid IN (modelid_1,modelid_2,modelid_3,modelid_4) WHERE entry=",
      "SELECT cmi.* FROM creature_model_info AS cmi JOIN creature_template ON modelid IN (modelid_1,modelid_2) WHERE entry=",
      "SELECT cmi.* FROM creature_model_info AS cmi JOIN creature_template ON modelid IN (modelid1,modelid2,modelid3,modelid4) WHERE entry=" /* TrinityCore, SunwellCore */),
      "",
      "Cannot access `creature_model_info` table in this DB",
      "Not defined in `creature_model_info`",
      "from `creature_model_info`"
    );
}


$res = MyOP(
"(SELECT *, 'DR' AS tableID from creature_loot_template WHERE entry=$crea->lootid)"
." UNION ".
"(SELECT *, 'SK' AS tableID from skinning_loot_template WHERE entry=$crea->skinloot)"
." UNION ".
"(SELECT *, 'PP' AS tableID from pickpocketing_loot_template WHERE entry=$crea->pickpocketloot)"
);
$loot = array();
$nl = 0;
$itemlist = "";
while($r = mysql_fetch_object($res)) {
  if (!isset($r->mincountOrRef))  continue;
  if ($r->mincountOrRef >= 0) {
      $loot[$nl++] = $r;
      $itemlist .= ($itemlist == "" ? "":",") . $r->item;
  }
  else {
     printf("  %5s%% x%-7s REF %s%s\n",
      floatfmt($r->ChanceOrQuestChance, 5),
      $r->maxcount,
      - $r->mincountOrRef,
      $r->groupid == 0 ? "" : " :".$r->groupid
     );
  }
}

if ($itemlist != "") {

$res = MyOP("SELECT * FROM item_template WHERE entry IN ($itemlist)");
$items = array();
while($r = mysql_fetch_object($res)) {
  $items[$r->entry] = $r;
}

for($i = 0; $i < $nl; $i++) {
   $l = & $loot[$i];
   PrintItem($items[ $l->item ],
     sprintf(" %7s x%-7s ",
      floatfmt($l->ChanceOrQuestChance, 5) . ($l->groupid == 0 ? '%' : ":$l->groupid"),
      $l->mincountOrRef == $l->maxcount ? $l->maxcount : "$l->mincountOrRef-$l->maxcount"
     ),
     @$l->condition_id == 0 ? "\n" : sprintf("  [COND %d]\n", $l->condition_id)
   );
}

}

if ($verbose)  echo readable(print_r($crea, true));

} // for all matching creatures

if ($ncreas == 0) die("Creature `$cname` not found in creature_template!\n");
printf("=== %d creatures === \n", $ncreas);

?>
