<?php

require("../../inc/config.inc");
$DEBUG=0;
//echo "nmicommand = $nmicommand<br>";
//echo "modified_data = $modified_data<br>";
//exit();
if (!isset($url))
    $url = "objShow.php";
if (!isset($timeout))
    $timeout = 15;

if (!isset($language))
    $language = "eng";


if($language == "chn"){
	$parameter = Array(
			saveiscompleted   => "保存完成",
			actioniscompleted => "任务完成",
			nobsscommresponse => "BssComm 没有回应",
			nobscresponse     => "BSC 没有回应",
			cmdtablefull      => "命令表没有空间，一会儿后再试"
		);
}else{
	$parameter = Array(
			saveiscompleted   => "Save is Completed: (modified items are highlighted)",
			actioniscompleted => "Action is completed",
			nobsscommresponse => "No response from BssComm",
			nobscresponse     => "No response from BSC",
			cmdtablefull      => "Command table is full: wait and send the command later"
		);
}

// Display_Type
define("DO_NOT_DISPLAY",0);
define("PULLDOWN_MENU",1);
define("TEXTBOX",2);
define("LABEL",3);
define("RADIO_BUTTON",4);
define("PUSH_BUTTON",5);
define("CHECKBOX",6);
define("TEXTAREA",7);
define("CONFIRM_PUSH_BUTTON",8);

// Attribute_Type
define("READONLY", 0);
define("NUMBERS", 1);
define("STRINGS", 2);
define("INTEGER_ARRAY", 3);

$bssDb = "BssOmcDb";
//
// if nothing has been modified, reload the original page
//

if ( ($modified_data == '') && ($nmicommand == ''))
{
    header("Location: " .
        "$url?language=$language&bssid=$bssid&objectid=$objectid" .
        "&tablename=$tablename" .
        "&status='Nothing is requested'" .
        (isset($x)?"&x=$x":"") .
        (isset($y)?"&y=$y":"")
    );
    return;
}

//
// Find the available row in OMCR_COMMAND to insert nmi commands
// Get 10 available and insert 2 nmi commands
// 1. oid $objectid
// 2. set $para1=$val1 [$para2=$val2] ...
//
function displayaction()
{
	echo "<img border=\"0\" src=\"../../images/arrow.gif\" width=\"10\" height=\"10\">";
	flush();
}
$dbname="BssOmcDb";
$hostname="localhost";
$username="root";
$password="rootaa";

$db = mysql_connect($hostname, $username, $password);
mysql_select_db($dbname,$db);

if ($nmicommand != '')
{
	$nmicmd = $nmicommand;
}
else if ($modified_data != '')
{
    //echo $modified_data . "<BR>";
    $parm_name = explode(",",$modified_data);
    $nmicmd="set";
    foreach ($parm_name as $attribute)
    {
	switch(${"t$attribute"})
	{
			
            case NUMBERS:
				$tmpSql="SELECT Attribute_Id FROM OMCR_Meta_Table WHERE Attribute_Name='$attribute'";
				$tmpResult = mysql_query($tmpSql,$db) or
					  die("Invalid query: $tmpSql\n" . mysqli_error($pubConn));
				$tmpRow = mysqli_fetch_row($tmpResult);
				$tmpStr=$tmpRow[0];
                
				if (${$attribute})
                {
                    //$nmicmd.=" $attribute=${$attribute}";
					$nmicmd.=" $tmpStr=${$attribute}";
                }
                else // for checkbox:  ${$attribute}=true or false
                {
                    //$nmicmd.=" $attribute=0";
					$nmicmd.=" $tmpStr=0";
                }
                break;
            case STRINGS:
				if($attribute=="Label"){
                $nmicmd.=" $attribute=\"" . rawurlencode(${$attribute}) . "\"";
			    }
				else
				{
					$tmpSql="SELECT Attribute_Id FROM OMCR_Meta_Table WHERE Attribute_Name='$attribute'";
					$tmpResult = mysql_query($tmpSql,$db) or
									die("Invalid query: $tmpSql\n" . mysqli_error($pubConn));
					$tmpRow = mysqli_fetch_row($tmpResult);
					$tmpStr=$tmpRow[0];
					//$nmicmd.=" $tmpStr=\"" . rawurlencode(${$attribute}) . "\"";
					$nmicmd.=" $tmpStr=\"" . (${$attribute}) . "\"";
					//echo "string == ${$attribute}";
				}
                break;
            case INTEGER_ARRAY:
                $tmpSql="SELECT Attribute_Id FROM OMCR_Meta_Table WHERE Attribute_Name='$attribute'";
				$tmpResult = mysql_query($tmpSql,$db) or
					  die("Invalid query: $tmpSql\n" . mysqli_error($pubConn));
				$tmpRow = mysqli_fetch_row($tmpResult);
				$tmpStr=$tmpRow[0];
                $stringarray = explode("_",$tmpStr);
				$nmicmd.= " $stringarray[0]=[$stringarray[1]=${$attribute}]";
                break;
            default:
                break;;
	}
        //echo $nmicmd . "<BR>";
    }
}

$sqlstring = "LOCK TABLES OMCR_COMMAND WRITE";
$res = mysqli_query($pubConn,$sqlstring) or
          die("Invalid query:$sqlstring\n" . mysqli_error($pubConn));
$sqlstring = "SELECT row_no FROM OMCR_COMMAND WHERE status=0 " .
             "ORDER BY seqNum ASC LIMIT 10";
//echo "$sqlstring<BR>";
$res = mysqli_query($pubConn,$sqlstring) or
          die("Invalid query:$sqlstring\n" . mysqli_error($pubConn));
while (list($row_no[]) = mysqli_fetch_row($res));
$no_of_rows = mysqli_num_rows($res);
mysql_free_result($res);

if ( $no_of_rows <= 0 || ($no_of_rows > 10) )
{
    //
    // No available row in OMCR_COMMAND
    // Send error to MySQL()
    //
    header("Location: " .
        "$url?language=$language&bssid=$bssid&objectid=$objectid" .
        "&tablename=$tablename" .
        "&status='{${$parameter}[cmdtablefull]}'" .
        (isset($x)?"&x=$x":"") .
        (isset($y)?"&y=$y":"")
    );
    return;
}

//
// Insert 2 commands in OMCR_COMMAND out of 10 possible available rows
//
$i=0;
do
{
    if ($row_no[$i] != '')
    {
        $sqlstring = "REPLACE INTO OMCR_COMMAND VALUES(" . $row_no[$i] .
                     ",$bssid,'oid $objectid',null,255,-1,null,null,null)";
        $res       = mysqli_query($pubConn,$sqlstring) or
                     die("Invalid query:$sqlstring\n" . mysqli_error($pubConn));
    }
    $i++;
} while ($i<10 && mysql_affected_rows() != 2);

$cmd1_row_no = $row_no[$i-1];

do
{
    if ($row_no[$i] != '')
    {
        $sqlstring = "REPLACE INTO OMCR_COMMAND VALUES(" .
                     $row_no[$i] . ",$bssid,'$nmicmd',null,255,-1,null,null,null)";
        $res       = mysqli_query($pubConn,$sqlstring) or
                     die("Invalid query:$sqlstring\n" . mysqli_error($pubConn));
    }
    $i++;
} while (mysql_affected_rows() != 2 && $i<10);
$cmd2_row_no = $row_no[$i-1];
//echo "cmd1_row_no=$cmd1_row_no,cmd2_row_no=$cmd2_row_no<br>";
$sqlstring = "UNLOCK TABLES";
$res = mysqli_query($pubConn,$sqlstring) or
          die("Invalid query:$sqlstring\n" . mysqli_error($pubConn));

//
// Wait for response: timeout value = $timeout
//
$timewait=0;
$interval=500000;   // in micro-seconds

while ($timewait < 1000000 * $timeout)
{			
    $resultcode=$responsecode=$result=$response=null;
    usleep($interval);
	//echo "<img border=\"0\" src=\"../../images/arrow.gif\" width=\"10\" height=\"10\">";
	//flush();
    $timewait += $interval;
	
    $sqlstring = "SELECT t1.resultcode,t1.responsecode," .
                 "t2.engStatInfo,t3.engStatInfo " .
                 "FROM OMCR_COMMAND AS t1,OMCR_STATCODE AS t2,OMCR_VARSTATCODE AS t3 " .
                 "WHERE t2.statcode=t1.resultcode AND t3.statcode=t1.responsecode " .
                 "AND t1.status=0 " .
                 "AND (t1.row_no=$cmd1_row_no OR t1.row_no=$cmd2_row_no) " .
                 "ORDER BY seqNum ASC";

    //echo "$sqlstring<BR>";
    $res       = mysqli_query($pubConn,$sqlstring) or
                 die("Invalid query:$sqlstring\n" . mysqli_error($pubConn));
    while ( $mydata = mysqli_fetch_row($res) )
    {
        list($resultcode[],$responsecode[],$result[],$response[]) = $mydata;
    }
    $no_of_rows = mysqli_num_rows($res);
	//echo "no_of_row=$no_of_rows<br>";
    mysql_free_result($res);

    if ($no_of_rows == 2)
    {
        if ($resultcode[0] != 0)  // 0='ok'
        {
            // Oid failed !!!
            header("Location: " .
                "$url?language=$language&bssid=$bssid" .
                "&objectid=$objectid&tablename=$tablename" .
                "&alarm=$result[0]" .
                (($responsecode[0]!=0)? " --- $response[0]":"") .
                (isset($x)?"&x=$x":"") .
                (isset($y)?"&y=$y":""));
			//echo "<script language=\"javascript\">";
			//$href="$url?language=$language&bssid=$bssid&objectid=$objectid&tablename=$tablename".
			//	"&objectid=$objectid&tablename=$tablename&alarm=$result[0]".
			//  "
			//echo "window.location.href='$href';";
			//echo "</script>";
			
        }
        elseif ($resultcode[1] != 0)
        {
            // Nmi command failed !!!
            header("Location: " .
                "$url?language=$language&bssid=$bssid" .
                "&objectid=$objectid&tablename=$tablename" .
                "&alarm=$result[1]" .
                (($responsecode[1]!=0)? " --- $response[1]":"") .
                (isset($x)?"&x=$x":"") .
                (isset($y)?"&y=$y":""));
        }
        else
        {
            // Success !!!
            header("Location: " .
                "$url?language=$language&bssid=$bssid" .
                "&objectid=$objectid" .
                "&tablename=$tablename" .
                ( (strncmp(strtolower($nmicommand), "create",6)
                  && strncmp(strtolower($nmicommand), "delete",6)
                  && (strncmp(strtolower($objectid),"abismgr",7) || strncmp(strtolower($nmicommand),"set adminstate=2",16))
                  )?
                 "&status={${$parameter}[saveiscompleted]}":
                 "&status={${$parameter}[actioniscompleted]}"
                ) .
//                (($nmicommand != '') ?  "&status={${$parameter}[actioniscompleted]}":
//                 "&status={${$parameter}[saveiscompleted]}") .
                (($modified_data == '') ? "":"&saved=$modified_data") .
                (isset($x)?"&x=$x":"") .
                (isset($y)?"&y=$y":"")
            );
        }
		
        return;
    }//end if
	
}//end while

    //
    // Server or BSC has no response
    // OMCR_COMMAND.status did not change to zero before timeout
    //
    $sqlstring = "SELECT * FROM OMCR_COMMAND " .
                 "WHERE status=254 AND (row_no=$cmd1_row_no OR row_no=$cmd2_row_no) ";
    //echo "sql>$sqlstring<BR>";
    $res = mysqli_query($pubConn,$sqlstring) or
           die("Invalid query:$sqlstring\n" . mysqli_error($pubConn));
	$test = mysqli_fetch_row($res);
	//echo "result>>$test<br>";
    if (mysqli_fetch_row($res))
    {
		echo "<br>";
        echo "<font color=red size=+3><b>No response from Bsc!!!</b></font>";
		echo "<br>";
		echo "<a href=\"JavaScript:history.go(-1)\"><img align=absBottom border=0 src=\"../../images/left.gif\" width=\"14\" height=\"14\">Back</a>";
    }
    else
    {
		echo "<br>";
		echo "<font color=red size=+3><b>No response from BssComm!!!</b></font>";
		echo "<br>";
		echo "<a href=\"JavaScript:history.go(-1)\"><img align=absBottom border=0 src=\"../../images/left.gif\" width=\"14\" height=\"14\">Back</a>";
    }

    //
    // Change status to 0
    //
    $sqlstring = "UPDATE OMCR_COMMAND SET status=0 WHERE row_no=$cmd1_row_no OR row_no=$cmd2_row_no";
    //echo "$sqlstring<BR>";
    $res = mysqli_query($pubConn,$sqlstring) or
           die("Invalid query:$sqlstring\n" . mysqli_error($pubConn));
?>
