<?php

include_once(dirname(__FILE__).'/../../Base/View.php');

class ServerView extends View
{
  var $ItemFormClass = array(
    'Title' => 'Nastavení',
    'Table' => 'Server',
    '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' => ''),
      'Database' => array('Type' => 'Database', 'Caption' => 'Databáze', 'Default' => 0),
      'ServerId' => array('Type' => 'Hidden', 'Caption' => 'Id', 'Default' => 0),
      'TimeCreate' => array('Type' => 'DateTime', 'Caption' => 'Datum založení', 'Default' => 'NOW()'),
      'NetworkPortRealmd' => array('Type' => 'Integer', 'Caption' => 'Port realmd', 'Default' => ''),
    ),
  );
  var $ItemListFormClass = array(
    'Title' => 'Server',
    'Table' => '(SELECT `Client`.`Version`, `Server`.`Name`, `Server`.`Homepage`, `Server`.`Id`, `Server`.`NetworkPortRealmd`, `User`.`Name` AS `UserName`, Server.Online, Server.CharacterOnlineCount, Server.CharacterCount, Server.AccountCount FROM `Server` JOIN `User` ON `User`.`Id` = `Server`.`User` JOIN `Database` ON `Database`.`Id` = `Server`.`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' => ''),
      'NetworkPortRealmd' => 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),
      'AccountCount' => array('Type' => 'Integer', 'Caption' => 'Účtů', 'Default' => 0),
      'CharacterCount' => array('Type' => 'Integer', 'Caption' => 'Postav', 0),
      'UserName' => array('Type' => 'String', 'Caption' => 'Správce', 'Default' => ''),
    ),
  );
  var $CreateFormClass = array(
    'Title' => 'Nový server',
    'Table' => 'Server',
    'SubmitText' => 'Registrovat',
    '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'),
    ),
  );
  var $EditFormClass = array(
    'Title' => 'Nastavení',
    'Table' => 'Server',
    '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'),
      'ServerId' => array('Type' => 'Hidden', 'Caption' => 'Id', 'Default' => 0),
      //'TimeCreation' => array('Type' => 'DateTime', 'Caption' => 'Datum založení', 'Default' => 'NOW()'),
    ),
  );
  var $GameAccountNewFormClass = array(
    'Title' => 'Vytvoření nového herního účtu',
    'Table' => '',
    'Items' => array(
      'Name' => array('Type' => 'String', 'Caption' => 'Přihlašovací jméno', 'Default' => ''),
      'Password' => array('Type' => 'Password', 'Caption' => 'Heslo', 'Default' => ''),
      'Password2' => array('Type' => 'Password', 'Caption' => 'Potvrzení hesla', 'Default' => ''),
      'Email' => array('Type' => 'String', 'Caption' => 'E-mail', 'Default' => ''),
      'Expansion' => array('Type' => 'ServerExpansion', 'Caption' => 'Rozšíření', 'Default' => 2),
      'ServerId' => array('Type' => 'Hidden', 'Caption' => 'Id', 'Default' => 0),
    ),
  );  
  
  function ShowListOnRow($Row)
  {
    $Row['NetworkPortRealmd'] = '<a href="?Module=Server&amp;Action=RealmList&amp;Id='.$Row['Id'].'">'.$Row['NetworkPortRealmd'].'</a>';
    if($Row['Homepage'] != '') $Row['Name'] = '<a href="'.$Row['Homepage'].'">'.$Row['Name'].'</a>';
    unset($Row['Homepage']);
    return($Row);
  }
  
  function ItemList()
  {
    $Output = '<h4>Seznam serverů</h4>';
    $Table = new Table($this->ItemListFormClass, $this->System);
    if(array_key_exists('Filter', $_GET))
    {
      if($_GET['Filter'] == 'User')
        $Table->Definition['Table'] = substr($Table->Definition['Table'], 0, -1).' WHERE User='.$this->System->Modules['User']->Data['Id'].')';
    }
    $Table->OnRow = array($this, 'ShowListOnRow');
    $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=Server&amp;Action=Show&amp;Id='.$Item['Id'].'">Podrobnosti</a>';
     unset($Table->Values[$Index]['Id']);
    }
    $Output .= $Table->Show();
    if($this->System->Modules['Permission']->Check('Server', 'Add')) 
    {
      $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server');
      $DbRow = $DbResult->fetch_row();
      $ServerCount = $DbRow[0];
      $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server WHERE User='.$this->System->Modules['User']->Data['Id']);
      $DbRow = $DbResult->fetch_row();
      if(($ServerCount < $this->Config['MaxServerCount']) and ($DbRow[0] < $this->Config['MaxServerCountPerUser']))
        $Output .= '<br /><div style="text-align: center;"><a href="?Module=Server&amp;Action=Add">Vytvořit nový server</a></div>';      
    }
    return($Output);
  }
  
  function Item()
  {
    $Id = $_GET['Id'];
    $Server = new Server($this->System, $Id);
    if(isset($Server->Server))
    {
    $Output = '<h4>Podrobnosti serveru</h4>';
    $Form = new Form($this->System, $this->ItemFormClass);
    $Form->LoadValuesFromDatabase($Id);
    $Form->Definition['Items']['Realmlist'] = array('Type' => 'String', 'Caption' => 'Adresa k připojení', 'Default' => '');    
    $Form->Definition['Items']['Uptime'] = array('Type' => 'String', 'Caption' => 'Doba běhu', 'Default' => '');
    $Form->Definition['Items']['UsedMemory'] = array('Type' => 'String', 'Caption' => 'Použitá paměť', 'Default' => '');    
    $Form->Definition['Items']['AccountCount'] = array('Type' => 'String', 'Caption' => 'Počet účtů', 'Default' => '');    
    $ServerStatus = $Server->GetState();
    $Form->Values['Realmlist'] = $this->Config['Web']['Host'].':'.$Form->Values['NetworkPortRealmd'];
    unset($Form->Definition['Items']['NetworkPortRealmd']);
    $Form->Values['Uptime'] = $this->System->AddPrefixMultipliers($ServerStatus['Uptime'], '', 4, 'Time');
    $Form->Values['UsedMemory'] = $this->System->AddPrefixMultipliers($ServerStatus['UsedMemory'] * 1024, 'B', 4, 'Binary');
    $Form->Values['AccountCount'] = $ServerStatus['AccountCount'];
    $Output .= $Form->ShowTable();
    $Output .= '<div style="text-align: center">';
    if($this->System->Modules['Permission']->Check('Server', 'Edit'))
    {
      $Output .= '<br /><a href="http://'.$this->System->Config['Web']['Host'].'/mysql/">Správa databáze</a> ';
      if(array_key_exists('Id', $Server->Server['Database']) and ($Server->Server['Lock'] == 0))
      {
        if($ServerStatus['RealmdPortState'] == true) $Output .= ' <a href="?Module=Server&amp;Action=Stop&amp;Id='.$Server->Id.'">Zastavit</a>  <a href="?Module=Server&amp;Action=Restart&amp;Id='.$Server->Id.'">Restartovat</a>';
          else $Output .= ' <a href="?Module=Server&amp;Action=Start&amp;Id='.$Server->Id.'">Spustit</a>';
      }
      if($Server->Server['Lock'] == 0)
      {
        $Output .= ' <a href="?Module=Server&amp;Action=Edit&amp;Id='.$Server->Id.'">Upravit základní nastavení</a>';
      }
      //$Output .= ' <a href="?Action=ServerDatabaseImport&amp;Id='.$Server->Id.'">Načtení čisté databáze</a>';
      $Output .= ' <a href="?Module=Realm&amp;Action=Add&amp;Id='.$Server->Id.'">Vytvořit nový svět</a>';
      $Output .= ' <a href="?Module=Realm&amp;Action=UpdateCharacters&amp;Id='.$Server->Id.'">Aktualizovat počty postav</a>';
    }
    $Output .= ' <a href="?Module=Server&amp;Action=GameAccountRegister&amp;Id='.$Server->Id.'">Vytvoření herního účtu</a>';
    $Output .= '</div>';
    
    // Show realmlist
    $RealmView = new RealmView($this->System);
    $Output .= $RealmView->ItemList();
    } else $Output = $this->System->SystemMessage('Zobrazení serveru', 'Server se zadaným id nenalezen.');
    return($Output);
  }
  
  function Add()
  {
    $Output = '';
    if($this->System->Modules['Permission']->Check('Server', 'Add'))
    {
      $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server');
      $DbRow = $DbResult->fetch_row();
      $ServerCount = $DbRow[0];
      if($ServerCount < $this->Config['MaxServerCount'])
      {
        $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server WHERE User='.$this->System->Modules['User']->Data['Id']);
        $DbRow = $DbResult->fetch_row();
        if($DbRow[0] >= $this->Config['MaxServerCountPerUser']) 
        	$Output .= $this->System->SystemMessage('Nový server', 'Na jeden účet lze vytvořit maximálně '.
        	  $this->Config['MaxServerCountPerUser'].' serverů');
        else 
        {
          $Form = new Form($this->System, $this->CreateFormClass);
          $Form->LoadValuesFromForm();
          $Form->OnSubmit = '?Action=ServerCreate';
          $Output .= 'Tento formulář vám umožní si vytvořit nový server. Pečlivě vyplňte požadované údaje.';
          $Output .= $Form->ShowEditForm();
        }
      } else $Output .= $this->System->SystemMessage('Nový server', 'Nelze vytvářet další servery');
    } else $Output = $this->System->SystemMessage('Vytvoření serveru', 'Nemáte oprávnění');
    return($Output);
  }
  
  function Create()
  {
    $Output = '';
    if($this->System->Modules['Permission']->Check('Server', 'Add'))
    {
      $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server WHERE User='.$this->System->Modules['User']->Data['Id']);
      $DbRow = $DbResult->fetch_row();
      if($DbRow[0] >= $this->Config['MaxServerCountPerUser']) 
      	$Output .= $this->System->SystemMessage('Nový server', 'Na jeden účet lze vytvořit maximálně '.
      		$this->Config['MaxServerCountPerUser'].' serverů');
      else 
      {
        $DbResult = $this->Database->query('SELECT MAX(NetworkPortRealmd) FROM Server');
        $DbRow = $DbResult->fetch_row();
        $NewPortRealmd = $DbRow[0] + 1;
        if($NewPortRealmd < $this->Config['BaseNetworkPortRealmd']) $NewPortRealmd = $this->Config['BaseNetworkPortRealmd'];
            
        $Form = new Form($this->System, $this->CreateFormClass, array());
        $Form->LoadValuesFromForm();
        $this->Database->insert('Server', array('Name' => $Form->Values['Name'], 'Description' => $Form->Values['Description'], 'User' => $this->System->Modules['User']->Data['Id'], 'Homepage' => $Form->Values['Homepage'], 'Database' => $Form->Values['Database'], 'NetworkPortRealmd' => $NewPortRealmd, 'Lock' => 1, 'TimeCreate' => 'NOW()'));
        $LastInsertId = $this->Database->insert_id;
        $Server = new Server($this->System, $LastInsertId);
        $Server->CreateDatabase();            
        $Output .= $this->System->SystemMessage('Vytvoření serveru', $Server->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 = $this->System->SystemMessage('Vytvoření serveru', 'Nemáte oprávnění');
    return($Output);
  }
  
  function Save()
  {
    $Output = '';
    $Server = new Server($this->System, $_POST['ServerId']);
    if(($this->System->Modules['User']->Data['Id'] == $Server->Server['User']) or 
    	($this->System->Modules['Permission']->Check('Server', 'Modify')))
    {
      $Form = new Form($this->System, $this->EditFormClass, array());
      $Form->LoadValuesFromForm();
      $ServerId = $_POST['ServerId'];
      unset($Form->Values['ServerId']);
      $Output .= $this->System->SystemMessage('Upravit server', 'Nastavení serveru uloženo.');
      $Form->SaveValuesToDatabase($_POST['ServerId']);
      $Form->OnSubmit = '?Action=ServerSave';
        
      $Server = new Server($this->System, $_POST['ServerId']);
      $Server->SaveConfiguration();
      $Form->Values['ServerId'] = $ServerId;
      $Output .= $Form->ShowEditForm();
    } else $Output = $this->System->SystemMessage('Nastavení serveru', 'Nemáte oprávnění');
    return($Output);
  }

  function Edit()
  {
    $Output = '';
    $Server = new Server($this->System, $_GET['Id']);
    if(($this->System->Modules['User']->Data['Id'] == $Server->Server['User']) or 
    	($this->System->Modules['Permission']->Check('Server', 'Modify')))
    {
      $Form = new Form($this->System, $this->EditFormClass);
      $Form->LoadValuesFromDatabase($_GET['Id']);
      $Form->Values['ServerId'] = $_GET['Id'];
      $Form->OnSubmit = '?Module=Server&amp;Action=Save';
      $Output .= $Form->ShowEditForm();
    } else $Output = $this->System->SystemMessage('Nastavení serveru', 'Nemáte oprávnění');
    return($Output);
  } 
  
  function Start()
  {
    $Output = '';
    if($this->System->Modules['Permission']->Check('Server', 'OwnerControl'))
    {
      $Server = new Server($this->System, $_GET['Id']);
      if(($this->System->Modules['User']->User['Id'] == $Server->Server['User']) or 
      	($this->System->Modules['Permission']->Check('Server', 'Control')))
      {
        $Output .= $this->System->SystemMessage('Spuštění serveru', $Server->Start());
        $TaskView = new TaskView($this->System);
        $Output .= $TaskView->ItemList();;
      } else $this->System->SystemMessage('Spuštění serveru', 'Nemáte oprávnění');
    } else $this->System->SystemMessage('Spuštění serveru', 'Nemáte oprávnění');
    return($Output);
  }
  
  function Stop()
  {
    $Output = '';
    if($this->System->Modules['Permission']->Check('Server', 'OwnerControl'))
    {
      $Server = new Server($this->System, $_GET['Id']);
      if(($this->System->Modules['User']->Data['Id'] == $Server->Server['User']) or 
      	($this->System->Modules['Permission']->Check('Server', 'Control')))
      {
        $Output .= $this->System->SystemMessage('Zastavení serveru', $Server->Stop());
        $TaskView = new TaskView($this->System);
        $Output .= $TaskView->ItemList();;
      } else $this->System->SystemMessage('Zastavení serveru', 'Nemáte oprávnění');
    } else $this->System->SystemMessage('Zastavení serveru', 'Nemáte oprávnění');
    return($Output);
  }
  
  function AccountCreate()
  {
    $Form = new Form($this->System, $this->GameAccountNewFormClass);
    $Form->LoadValuesFromForm();
    $Form->Values['ServerId'] = $_GET['Id'];
    $Form->OnSubmit = '?Module=Server&amp;Action=GameAccountRegisterFinish';
    $Output = $Form->ShowEditForm();
    return($Output);
  }  
  
  function AccountCreateFinish()
  {
    $Form = new Form($this->System, $this->GameAccountNewFormClass);
    $Form->LoadValuesFromForm();
    $Server = new Server($this->System, $Form->Values['ServerId']);
    $Output = $this->System->SystemMessage('Vytvoření herního účtu', $Server->NewAccount($Form->Values['Name'], $Form->Values['Password'], $Form->Values['Password2'], $Form->Values['Email'], $Form->Values['Expansion']));
    $Output .= '<a href="?Module=Server&amp;Action=GameAccountRegister&amp;Id='.$Form->Values['ServerId'].'">Zpět k zadání údajů</a>';
    return($Output);
  }
  
  function RealmListFile()
  {
    if(array_key_exists('Id', $_GET))
    {
      Header('Content-Type: text/plain');
      Header('Content-Disposition: attachment; filename="realmlist.wtf"');
      $Server = new Server($this->System, $_GET['Id']);
      $Output = array(
        'set realmlist '.$this->Config['Web']['Host'].':'.$Server->Server['NetworkPortRealmd'],
        'set patchlist '.$this->Config['Web']['Host'].':'.$Server->Server['NetworkPortRealmd'],
        'set portal eu',
      );
      echo(implode("\n", $Output));
    } else echo('Musíte zadat Id serveru');
  }

  function PatchList()
  {
    Header('Content-type: text/plain');
    if(array_key_exists('Id', $_GET))
    {
      $Server = new Server($this->System, $_GET['Id'] * 1);
      echo($Server->GetPatchList());
    } else echo('Zadané id serveru nenalezeno.');
  }
  
  function XMLExport()
  {
    Header('Content-Type: application/xml');

    $Output = '<?xml version="1.0" encoding="utf-8"?>';
    if(array_key_exists('File', $_GET))
    {
      Header('Content-Disposition: filename="'.$_GET['File'].'.xml"');
      if($_GET['File'] == 'ServerList')
      {
        $Output .= '<serverlist version="1.0">';
        $DbResult = $this->Database->query('SELECT * FROM Server');
        while($Server = $DbResult->fetch_assoc())
        {
          $Output .= '<server>'.
          '<name>'.$Server['Name'].'</name>'.
          //'<playermaxcount>'.$Server['PlayerMaxCount'].'</playermaxcount>'.
          //'<playeronlinecount>'.$Server['PlayerOnlineCount'].'</playeronlinecount>'.
          '<homepage>'.$Server['Homepage'].'</homepage>'.
          '</server>';
        }
        $Output .= '</serverlist>';
      }
    } else $Output .= '<document/>';
    $Html = new Html();
    if($this->Config['Web']['FormatHTML'] == true) echo($Html->FormatOutput($Output));
      else echo($Output);
  }  
}
