<?php

namespace WoWPress\Frontend\Widgets;

use PlanetTeamSpeak\TeamSpeak3Framework\Exception\TeamSpeak3Exception;
use PlanetTeamSpeak\TeamSpeak3Framework\TeamSpeak3;

class Teamspeak extends Widget {

    protected $template_path = "teamspeak.php";
    protected $title = "TS-Status";
    protected $base_id = "wowpress_teamspeak";
    public $name = "TS-Status";
    public $error = false;
    protected $restricted = "wowpress_view_teamspeak";
    public $ts_server;


    public function init($instance){
        $ip = $instance['ip'];
        $port = $instance['port'];
        $telnet = $instance['telnet'];

        if(empty($ip) || empty($port) || empty($telnet)){
            $this->error = "Server konnte nicht gefunden werden.";
        }else{
            $uri = "serverquery://$ip:$telnet/?server_port=$port&blocking=0&timeout=2";
            try{
                $this->ts_server = TeamSpeak3::factory($uri);
            }catch(TeamSpeak3Exception $e){
                $this->error = $e->getMessage();
            }
        }


    }


    public function form( $instance ) {
		$ip = ! empty( $instance['ip'] ) ? $instance['ip'] : "";
		$port = ! empty( $instance['port'] ) ? $instance['port'] : "";
		$telnet = ! empty( $instance['telnet'] ) ? $instance['telnet'] : "";


		?>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'ip' ) ); ?>"><?php echo esc_html__( 'Server-IP', 'wowpress' ); ?></label>
			<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'ip' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'ip' ) ); ?>" type="text" value="<?php echo esc_attr( $ip ); ?>">
		</p>
        <p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'port' ) ); ?>"><?php echo esc_html__( 'Server-Port', 'wowpress' ); ?></label>
			<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'port' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'port' ) ); ?>" type="number" value="<?php echo esc_attr( $port ); ?>">
		</p>
        <p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'telnet' ) ); ?>"><?php echo esc_html__( 'Telnet-Port', 'wowpress' ); ?></label>
			<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'telnet' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'telnet' ) ); ?>" type="number" value="<?php echo esc_attr( $telnet ); ?>">
		</p>
		<?php
	}

	public function update( $new_instance, $old_instance ) {
		$instance          = array();
		$instance['ip'] = ( ! empty( $new_instance['ip'] ) ) ? strip_tags( $new_instance['ip'] ) : '';
		$instance['port'] = ( ! empty( $new_instance['port'] ) ) ? strip_tags( $new_instance['port'] ) : '';
		$instance['telnet'] = ( ! empty( $new_instance['telnet'] ) ) ? strip_tags( $new_instance['telnet'] ) : '';

		return $instance;
	}

}