<?php

include_once(dirname(__FILE__).'/../../Base/View.php');

class RealmView extends View
{
  var $ItemFormClass = array(
    'Title' => 'Nastavení světa',
    'Table' => 'Realm',
    'SubmitText' => 'Uložit',
    'Items' => array(
      'Name' => array('Type' => 'String', 'Caption' => 'Název', 'Default' => 'WoW server'),
      'Description' => array('Type' => 'Text', 'Caption' => 'Popis', 'Default' => ''),
      'Type' => array('Type' => 'ServerType', 'Caption' => 'Typ', 'Default' => 0),
      'Database' => array('Type' => 'Database', 'Caption' => 'Databáze', 'Default' => 0),
      'Motd' => array('Type' => 'String', 'Caption' => 'Zpráva dne', 'Default' => 'Vítejte na free WoW serveru'),
      'RealmId' => array('Type' => 'Hidden', 'Caption' => 'Id', 'Default' => 0),
      'TimeCreate' => array('Type' => 'DateTime', 'Caption' => 'Datum založení', 'Default' => 'NOW()'),
      'NetworkPortWorldd' => array('Type' => 'Integer', 'Caption' => 'Port realmd', 'Default' => ''),
    ),
  );
  var $ItemListFormClass = array(
    'Title' => 'Světy',
    'Table' => '(SELECT `Client`.`Version`, `Realm`.`Name`, `Realm`.`Id`, `Server`.`Name` AS `ServerName`, `Realm`.`NetworkPortWorldd`, Realm.Online, Realm.CharacterOnlineCount, Realm.CharacterCount FROM `Realm` JOIN `Server` ON `Server`.`Id` = `Realm`.`Server` JOIN `Database` ON `Database`.`Id` = `Realm`.`Database` JOIN `Emulator` ON `Emulator`.`Id` = `Database`.`Emulator` JOIN `Client` ON `Client`.`Id` = `Emulator`.`Client`)',
    'Items' => array(
      'Name' => array('Type' => 'String', 'Caption' => 'Název', 'Default' => ''),
      'NetworkPortWorldd' => array('Type' => 'Integer', 'Caption' => 'Realmlist', 'Default' => ''),
      'Version' => array('Type' => 'Integer', 'Caption' => 'Verze', 'Default' => 0),
      'Online' => array('Type' => 'OnlineState', 'Caption' => 'Stav', 'Default' => 0),
      'CharacterOnlineCount' => array('Type' => 'Integer', 'Caption' => 'Hráčů online', 'Default' => 0),
      'CharacterCount' => array('Type' => 'Integer', 'Caption' => 'Postav', 0),
      'ServerName' => array('Type' => 'String', 'Caption' => 'Server', 'Default' => ''),
    ),
  );
  var $CreateFormClass = array(
    'Title' => 'Nový svět',
    'Table' => 'Realm',
    'SubmitText' => 'Vytvořit',
    'Items' => array(
      'Name' => array('Type' => 'String', 'Caption' => 'Název', 'Default' => 'Svět'),
      'Description' => array('Type' => 'Text', 'Caption' => 'Popis', 'Default' => ''),
      'Homepage' => array('Type' => 'Hyperlink', 'Caption' => 'Webové stránky', 'Default' => ''),
      'Type' => array('Type' => 'ServerType', 'Caption' => 'Typ', 'Default' => 0),
      'Database' => array('Type' => 'Database', 'Caption' => 'Databáze', 'Default' => 0),
      'Motd' => array('Type' => 'String', 'Caption' => 'Zpráva dne', 'Default' => 'Vítejte na free WoW serveru'),
    ),
  );
  var $EditFormClass = array(
    'Title' => 'Nastavení',
    'Table' => 'Realm',
    'SubmitText' => 'Uložit',
    'Items' => array(
      'Name' => array('Type' => 'String', 'Caption' => 'Název', 'Default' => 'WoW server'),
      'Description' => array('Type' => 'Text', 'Caption' => 'Popis', 'Default' => ''),
      'Homepage' => array('Type' => 'Hyperlink', 'Caption' => 'Webové stránky', 'Default' => ''),
      'Type' => array('Type' => 'ServerType', 'Caption' => 'Typ', 'Default' => 0),
      'Database' => array('Type' => 'Database', 'Caption' => 'Databáze', 'Default' => 0),
      'Motd' => array('Type' => 'String', 'Caption' => 'Zpráva dne', 'Default' => 'Vítejte na free WoW serveru'),
      'RealmId' => array('Type' => 'Hidden', 'Caption' => 'Id', 'Default' => 0),
      //'TimeCreation' => array('Type' => 'DateTime', 'Caption' => 'Datum založení', 'Default' => 'NOW()'),
    ),
  );
  var $SettingDetailedFormClass = array(
    'Title' => 'Podrobné nastavení serveru',
    'Table' => '',
    'Items' => array(
      'RealmId' => array('Type' => 'Hidden', 'Caption' => 'Id', 'Default' => 0),
      'PlayerLimit' => array('Type' => 'Integer', 'Caption' => 'Max. počet hráčů online', 'Default' => 100),
      'PlayerSaveInterval' => array('Type' => 'Integer', 'Caption' => 'Perioda ukládání postav hráčů do databáze', 'Default' => 60000),
      'vmap_enableLOS' => array('Type' => 'Boolean', 'Caption' => 'Povolení systému Line-of-sight', 'Default' => 0),
      'UpdateUptimeInterval' => array('Type' => 'Integer', 'Caption' => 'Perioda aktualizace doby běhu světa v databázi', 'Default' => 10),
      'GameType' => array('Type' => 'GameType', 'Caption' => 'Typ světa', 'Default' => 0),
      'Motd' => array('Type' => 'String', 'Caption' => 'Zpráva dne zobrazovaná hráčům při přihlášení', 'Default' => 'Vítej hráči!'),
      'SkipCinematics' => array('Type' => 'SkipCinematics', 'Caption' => 'Zobrazovat úvodní video', 'Default' => ''),
      'StartPlayerLevel' => array('Type' => 'Integer', 'Caption' => 'Počáteční úroveň hráčů', 'Default' => 1),
      'MaxPlayerLevel' => array('Type' => 'Integer', 'Caption' => 'Max. úroveň hráčů', 'Default' => 80),
      'StartHeroicPlayerLevel' => array('Type' => 'Integer', 'Caption' => 'Počáteční úroveň hrdinských postav', 'Default' => 55),
      'StartPlayerMoney' => array('Type' => 'Integer', 'Caption' => 'Počáteční množství peněz', 'Default' => 0),
      'StartHonorPoints' => array('Type' => 'Integer', 'Caption' => 'Počáteční počet bodů cti', 'Default' => 0),
      'MaxHonorPoints' => array('Type' => 'Integer', 'Caption' => 'Max. počet bodů cti', 'Default' => 75000),
      'StartArenaPoints' => array('Type' => 'Integer', 'Caption' => 'Počáteční počet bodů arén', 'Default' => 0),
      'MaxArenaPoints' => array('Type' => 'Integer', 'Caption' => 'Max. počet bodů arén', 'Default' => 5000),
      'MaxArenaPoints' => array('Type' => 'Integer', 'Caption' => 'Max. počet bodů arén', 'Default' => 5000),
      'InstantLogout' => array('Type' => 'SecurityLevel', 'Caption' => 'Povolit okamžitého odhlášení', 'Default' => 1),
      'DisableWaterBreath' => array('Type' => 'SecurityLevel', 'Caption' => 'Zakázat dýchání pod vodou', 'Default' => 1),          
      'AllFlightPaths' => array('Type' => 'Boolean', 'Caption' => 'Povoleny všechny létací cesty', 'Default' => 0),          
      'AlwaysMaxSkillForLevel' => array('Type' => 'Boolean', 'Caption' => 'Vždy max. dovednost na úroveň', 'Default' => 0),          
      'ActivateWeather' => array('Type' => 'Boolean', 'Caption' => 'Aktivní počasí', 'Default' => 1),          
      'CastUnstuck' => array('Type' => 'Boolean', 'Caption' => 'Povolit odblokovací kouzlo pomocí .start', 'Default' => 1),          
      'MinPetitionSigns' => array('Type' => 'Integer', 'Caption' => 'Min. počet podpisů k zápisu spolku', 'Default' => 9),          
      'MaxGroupXPDistance' => array('Type' => 'Integer', 'Caption' => 'Max. rozdíl XP ve skupině', 'Default' => 74),          
      'MailDeliveryDelay' => array('Type' => 'Integer', 'Caption' => 'Zpoždění doručení pošty', 'Default' => 3600),          
      'Event_Announce' => array('Type' => 'Boolean', 'Caption' => 'Ohlašování událostí', 'Default' => 0),          
      'AllowTwoSide_Accounts' => array('Type' => 'Boolean', 'Caption' => 'Povolit účty s postavami obou stran', 'Default' => 0),          
      'AllowTwoSide_Interaction_Chat' => array('Type' => 'Boolean', 'Caption' => 'Povolit komunikaci mezi stranami', 'Default' => 0),          
      'AllowTwoSide_Interaction_Channel' => array('Type' => 'Boolean', 'Caption' => 'Povolit kanály mezi stranami', 'Default' => 0),
      'AllowTwoSide_WhoList' => array('Type' => 'Boolean', 'Caption' => 'Povolit obě strany v seznamu přítomných', 'Default' => 0),
      'Rate_XP_Kill' => array('Type' => 'Integer', 'Caption' => 'Násobek získaných zkušeností za zabití', 'Default' => 1),
      'Rate_XP_Quest' => array('Type' => 'Integer', 'Caption' => 'Násobek získaných zkušeností za dokončení výpravy', 'Default' => 1),
      'Rate_XP_Explore' => array('Type' => 'Integer', 'Caption' => 'Násobek získaných zkušeností za objevení oblasti', 'Default' => 1),
      'Ra_Enable' => array('Type' => 'Boolean', 'Caption' => 'Povolení vzdálená konzoly.', 'Default' => 0),
    ),
  );  

  function ItemList()
  {
    if(array_key_exists('Id', $_GET)) $ServerId = $_GET['Id'];
    
    $Realm = new Realm($this->System, 0);
    //$Realm->UpdateServerList();
    $Output = '<h4>Seznam světů</h4>';
    $Table = new Table($this->ItemListFormClass, $this->System);
    //$Table->OnRow = array($this, 'ShowRealmListOnRow');
    $Table->Definition['Table'] = substr($Table->Definition['Table'], 0, -1).' WHERE `Realm`.`Server`='.$ServerId.')';
    $Table->Definition['Items']['Id'] = array('Type' => 'Hidden', 'Caption' => '', 'Default' => '');
    $Table->LoadValuesFromDatabase($this->Database);
    $Table->Definition['Items']['Actions'] = array('Type' => 'String', 'Caption' => '', 'Default' => '');
    foreach($Table->Values as $Index => $Item)
    {
     $Table->Values[$Index]['Actions'] = '<a href="?Module=Realm&amp;Action=Show&amp;Id='.$Item['Id'].'">Podrobnosti</a>';
     unset($Table->Values[$Index]['Id']);
    }
    $Output .= $Table->Show();
    if($this->System->Modules['Permission']->Check('Realm', 'Add'))
    {
      $DbResult = $this->Database->query('SELECT COUNT(*) FROM Realm');
      $DbRow = $DbResult->fetch_row();
      $RealmCount = $DbRow[0];
      //$DbResult = $this->Database->query('SELECT COUNT(*) FROM Realm WHERE Server='.$this->System->Modules['User']->User['Id']);
      //$DbRow = $DbResult->fetch_row();
      if(($RealmCount < $this->Config['MaxRealmPerServerCount']))
        $Output .= '<br /><div style="text-align: center;"><a href="?Module=Realm&amp;Action=Add">Vytvořit nový svět</a></dev>';      
    }
    return($Output);
  } 
  
  function Item()
  {
    $Id = $_GET['Id'];
    $Realm = new Realm($this->System, $Id);
    //if(isset($Server->Server))
    //{
    $Output = '<h4>Podrobnosti světa</h4>';
    $Form = new Form($this->System, $this->ItemFormClass);
    $Form->LoadValuesFromDatabase($Id);
    $Form->Definition['Items']['Uptime'] = array('Type' => 'String', 'Caption' => 'Doba běhu', 'Default' => '');
    $Form->Definition['Items']['UsedMemory'] = array('Type' => 'String', 'Caption' => 'Použitá paměť', 'Default' => '');    
    $RealmStatus = $Realm->GetState();
    unset($Form->Definition['Items']['NetworkPortWorldd']);
    $Form->Values['Uptime'] = $this->System->AddPrefixMultipliers($RealmStatus['Uptime'], '', 4, 'Time');
    //$Form->Values['UsedMemory'] = $this->System->AddPrefixMultipliers($RealmStatus['UsedMemory'] * 1024, 'B', 4, 'Binary');
    $Output .= $Form->ShowTable();
    $Output .= '<div style="text-align: center">';
    if($this->System->Modules['Permission']->Check('Realm', 'Edit'))
    {
      $Output .= '<br /><a href="http://'.$this->System->Config['Web']['Host'].'/mysql/">Správa databáze</a> ';
      if(array_key_exists('Id', $Realm->Data['Database']) and ($Realm->Data['Lock'] == 0))
      {
        if($RealmStatus['WorlddPortState'] == true) $Output .= ' <a href="?Module=Realm&amp;Action=Stop&amp;Id='.$Realm->Id.'">Zastavit</a>  <a href="?Module=Realm&amp;Action=Restart&amp;Id='.$Realm->Id.'">Restartovat</a>';
          else $Output .= ' <a href="?Module=Realm&amp;Action=Start&amp;Id='.$Realm->Id.'">Spustit</a>';
      }
      if($Realm->Data['Lock'] == 0)
      {
        $Output .= ' <a href="?Module=Realm&amp;Action=Edit&amp;Id='.$Realm->Id.'">Upravit základní nastavení</a>';
        $Output .= ' <a href="?Module=Realm&amp;Action=EditDetailed&amp;Id='.$Realm->Id.'">Upravit podrobné nastavení</a>';
        $Output .= ' <a href="?Module=Realm&amp;Action=InitDatabase&amp;Id='.$Realm->Id.'">Vynulovat databázi</a>';
      }
      $Output .= ' <a href="?Module=Debug&amp;Action=ItemList&amp;Id='.$Realm->Id.'">Ladící informace</a>';
      //$Output .= ' <a href="?Action=ServerDatabaseImport&amp;Id='.$Server->Id.'">Načtení čisté databáze</a>';
    }
    $Output .= '</div>';    
    return($Output);
  } 
  
  function Add()
  {
    if(array_key_exists('Id', $_GET))
    {
      $ServerId = $_GET['Id']; 
    $Output = '';
    if($this->System->Modules['Permission']->Check('Realm', 'Add'))
    {
      $DbResult = $this->Database->query('SELECT COUNT(*) FROM Realm');
      $DbRow = $DbResult->fetch_row();
      $RealmCount = $DbRow[0];
      if($RealmCount < $this->Config['MaxRealmCount'])
      {
        if($this->System->Modules['User']->RealmCount() >= $this->Config['MaxServerCountPerUser'])
        	$Output .= $this->System->SystemMessage('Nový svět', 'Na jeden účet lze vytvořit maximálně '.
        		$this->Config['MaxServerCountPerUser'].' světů');
        else 
        {
          $Form = new Form($this->System, $this->CreateFormClass);
          $Form->LoadValuesFromForm();
          $Form->OnSubmit = '?Module=Realm&amp;Action=Create&amp;Id='.$ServerId;
          $Output .= 'Tento formulář vám umožní si vytvořit nový svět. Pečlivě vyplňte požadované údaje.';
          $Output .= $Form->ShowEditForm();
        }
      } else $Output .= $this->System->SystemMessage('Nový svět', 'Nelze vytvářet další světyservery');
    } else $Output .= USER_BAD_ROLE;
    } else $Output = $this->System->SystemMessage('Vytvoření světa', 'Nezadáno Id serveru');
    return($Output);
  }

  function Create()
  {
    if(array_key_exists('Id', $_GET))
    {
      $ServerId = $_GET['Id']; 
    if($this->System->Modules['Permission']->Check('Realm', 'Add'))
    {
      if($this->System->Modules['User']->RealmCount() >= $this->Config['MaxServerCountPerUser']) 
      	$Output = $this->System->SystemMessage('Nový svět', 'Na jeden účet lze vytvořit maximálně '.
      	$this->Config['MaxServerCountPerUser'].' světů');
      else 
      {
        // Allocate unused network port for realm
        $DbResult = $this->Database->query('SELECT MAX(NetworkPortWorldd) FROM Realm');
        $DbRow = $DbResult->fetch_row();
        $NewPortWorldd = $DbRow[0] + 1;
        if($NewPortWorldd < $this->Config['BaseNetworkPortWorldd']) $NewPortWorldd = $this->Config['BaseNetworkPortWorldd'];
            
        $Form = new Form($this->System, $this->CreateFormClass, array());
        $Form->LoadValuesFromForm();
        $this->Database->insert('Realm', array('Name' => $Form->Values['Name'], 'Description' => $Form->Values['Description'], 'Server' => $ServerId, 'Motd' => $Form->Values['Motd'], 'Homepage' => $Form->Values['Homepage'], 'Type' => $Form->Values['Type'], 'Database' => $Form->Values['Database'], 'NetworkPortWorldd' => $NewPortWorldd, 'Lock' => 1, 'TimeCreate' => 'NOW()'));
        $LastInsertId = $this->Database->insert_id;
        $Realm = new Realm($this->System, $LastInsertId);
        $Realm->CreateDatabase();            
        $Output = $this->System->SystemMessage('Vytvoření světu', $Realm->ImportDatabase(true));
        $TaskView = new TaskView($this->System);
        $Output .= $TaskView->ItemList();
        //$UserOptions->LoadValuesFromDatabase($this->System->Modules['User']->User['Id']);
        //$Form->OnSubmit = '?Action=ServerCreate';
        //$Output .= $Form->ShowEditForm();
      }
    } else $Output = USER_BAD_ROLE;
    } else $Output = $this->System->SystemMessage('Vytvoření světa', 'Nezadáno Id serveru');
    return($Output);
  }
  
  function Save()
  {
    $Output = '';
    $Realm = new Realm($this->System, $_POST['RealmId']);
    if($this->System->Modules['Permission']->Check('Realm', 'Save', $Realm->Id))
    {
      $Form = new Form($this->System, $this->EditFormClass, array());
      $Form->LoadValuesFromForm();
      $RealmId = $_POST['RealmId'];
      unset($Form->Values['RealmId']);
      $Output .= $this->System->SystemMessage('Upravit svět', 'Nastavení světa uloženo.');
      $Form->SaveValuesToDatabase($_POST['RealmId']);
      $Form->OnSubmit = '?Module=Realm&amp;Action=Save';
        
      $Realm = new Realm($this->System, $_POST['RealmId']);
      $Realm->SaveConfiguration();
      $Form->Values['RealmId'] = $RealmId;
      $Output .= $Form->ShowEditForm();
    } else $Output = $this->System->SystemMessage('Nastavení serveru', 'Nemáte oprávnění');
    return($Output);
  }

  function Edit()
  {
    $Output = '';
    $Realm = new Realm($this->System, $_GET['Id']);
    if($this->System->Modules['Permission']->Check('Realm', 'Edit', $Realm->Id))
    {
      $Form = new Form($this->System, $this->EditFormClass);
      $Form->LoadValuesFromDatabase($_GET['Id']);
      $Form->Values['RealmId'] = $_GET['Id'];
      $Form->OnSubmit = '?Module=Realm&amp;Action=Save';
      $Output .= $Form->ShowEditForm();
    } else $Output = $this->System->SystemMessage('Nastavení světa', 'Nemáte oprávnění');
    return($Output);
  }
  
  function EditDetailed()
  {
    $Output = '';
    $Realm = new Realm($this->System, $_GET['Id']);
    if($this->System->Modules['Permission']->Check('Realm', 'EditDetailed', $Realm->Id))
    {
      $Form = new Form($this->System, $this->SettingDetailedFormClass);
      $EmulatorConfig = new MangosConfigurationFile($this->System);
      $EmulatorConfig->Load('../realm/'.$Realm->Id.'/etc/mangosd.conf');
      $Form->Values = array();
      foreach($EmulatorConfig->ParameterList as $Index => $Item)
        $Form->Values[str_replace('.', '_', $Index)] = $Item;
      $Form->Values['RealmId'] = $_GET['Id'];
      $Form->OnSubmit = '?Module=Realm&amp;Action=SaveDetailed';
      $Output .= $Form->ShowEditForm();
    } else $this->System->SystemMessage('Nastavení světa', 'Nemáte oprávnění');
    return($Output);    
  }
  
  function SaveDetailed()
  {
    $Output = '';
    $Realm = new Realm($this->System, $_POST['RealmId']);
    if($this->System->Modules['Permission']->Check('Realm', 'SaveDetailed', $Realm->Id))
    {
      $Form = new Form($this->System, $this->SettingDetailedFormClass, array());
      $Form->LoadValuesFromForm();
      $EmulatorConfig = new MangosConfigurationFile($this->System);
      $EmulatorConfig->Load('../realm/'.$Realm->Id.'/etc/mangosd.conf');
      foreach($Form->Definition['Items'] as $Index => $Item)
      {
        if(!array_key_exists($Index, $Form->Values)) 
          $Form->Values[$Index] = 0;
        $EmulatorConfig->ParameterList[str_replace('_', '.', $Index)] = $Form->Values[$Index];
      }
      $EmulatorConfig->Save('../realm/'.$Realm->Id.'/etc/mangosd.conf');
      $RealmId = $_POST['RealmId'];
      unset($Form->Values['RealmId']);
      $Output .= $this->System->SystemMessage('Upravit svět', 'Nastavení světa uloženo.');
      //$Form->SaveValuesToDatabase($_POST['ServerId']);
      $Form->OnSubmit = '?Module=Realm&amp;Action=SaveDetailed';
       
      $Realm = new Realm($this->System, $_POST['RealmId']);
      $Realm->SaveConfiguration();
      $Form->Values['RealmId'] = $RealmId;
      $Output .= $Form->ShowEditForm();
    } else $this->System->SystemMessage('Nastavení světa', 'Nemáte oprávnění');
    return($Output);
  }
  
  function Start()
  {
    $Output = '';
    $Realm = new Realm($this->System, $_GET['Id']);
    if($this->System->Modules['Permission']->Check('Realm', 'Start', $Realm->Id))
    {
      $Output .= $this->System->SystemMessage('Spuštění serveru', $Realm->Start());
      $TaskView = new TaskView($this->System);
      $Output .= $TaskView->ItemList();;
    } else $this->System->Modules['Permission']->AccessDenied();
    return($Output);
  }
  
  function Stop()
  {
    $Output = '';
    $Realm = new Realm($this->System, $_GET['Id']);
    if($this->System->Modules['Permission']->Check('Realm', 'Stop', $Realm->Id))
    {
      $Output .= $this->System->SystemMessage('Zastavení serveru', $Realm->Stop());
      $TaskView = new TaskView($this->System);
      $Output .= $TaskView->ItemList();;
    } else $this->System->Modules['Permission']->AccessDenied();
    return($Output);
  }
  
  function InitDatabase()
  {
    if(array_key_exists('Id', $_GET))
    {
      $RealmId = $_GET['Id']; 
      $Realm = new Realm($this->System, $RealmId);
      if($this->System->Modules['Permission']->Check('Realm', 'InitDatabase', $Realm->Id))
      {
        $Output = $this->System->SystemMessage('Vynulování databáze', $Realm->ImportDatabase(true));
        $TaskView = new TaskView($this->System);
        $Output .= $TaskView->ItemList();
        //$UserOptions->LoadValuesFromDatabase($this->System->Modules['User']->User['Id']);
        //$Form->OnSubmit = '?Action=ServerCreate';
          //$Output .= $Form->ShowEditForm();
      } else $this->System->Modules['Permission']->AccessDenied();
    } else $Output = $this->System->SystemMessage('Vynulování databáze', 'Nezadáno Id serveru');
    return($Output);
  }
}
