<?php
    session_start();
	if ( empty($_SESSION['login']) ) {
        header( 'Location: login.php' );
        die;
	}

    include 'include/database.php';

    $connection = connect($database);

    $canAdmin = canAdministrate($connection, $_SESSION['login']);

    if ($canAdmin) {
        $campus = $_GET['campus'];
        $building = $_GET['building'];
        $room = $_GET['room'];

        $variables = array();
        $stringcmps = array();
        $structures = array();
        $events = array();

		$numDevices = 0;
		$room_id = getRoomIdCG($connection, $campus, $building, $room);
        $devices = getDevicesCG($connection, $room_id);

		foreach($devices as $device) {
            $structure = array();
            $numDevices++;

			$caption = $device['caption'];
			//$device = $device['name'];
			$id = $device['id'];

            $properties = getDevicePropertiesCG($connection, $device['id']);

            $numProps = 0;

            foreach($properties as $prop) {
                $numProps++;

                switch($prop['tracker']) {
                    case 'CHANNEL':
                        $type = 'usmTypeChannel';
                        array_push($events, "\tchannel_event[{$device['name']},{$prop['altname']}]	// {$device['caption']} - {$prop['name']}
	{
		on:
		{
			If ( usmDebug ) send_string 0, \"'###############################################################'\"
			If ( usmDebug ) send_string 0, \"'Channel: ', itoa(channel.channel)\"
			call 'usmSetValByNdx'($numDevices, $numProps, getHash( $numDevices, $numProps, itoa([{$device['name']}, {$prop['altname']}])))
		}
		off:
		{
			If ( usmDebug ) send_string 0, \"'###############################################################'\"
			If ( usmDebug ) send_string 0, \"'Channel: ', itoa(channel.channel)\"
			call 'usmSetValByNdx'($numDevices, $numProps, getHash( $numDevices, $numProps, itoa([{$device['name']}, {$prop['altname']}])))
		}
	}\n");
                        break;
                    case 'LEVEL':
                        $type = 'usmTypeLevel';
                        array_push($events, "\tlevel_event[{$device['name']},{$prop['altname']}]	// {$device['caption']} - {$prop['name']}
	{
		If ( usmDebug ) send_string 0, \"'###############################################################'\"
		If ( usmDebug ) send_string 0, \"'Level  : ', itoa(level.value)\"
		call 'usmSetValByNdx'($numDevices, $numProps, getHash( $numDevices, $numProps, itoa(level.value)))
	}\n");
                        break;
                    case 'NUMBER':
                        $type = 'usmTypeNumber';
                        array_push($variables, "\tvolatile double usmNum_{$prop['altname']}");
                        array_push($stringcmps, "\t\tcall 'usmNumCheck' ( $numDevices, $numProps, {$prop['altname']} )");
                        break;
                    case 'STRING':
                        $type = 'usmTypeString';
                        array_push($variables, "\tvolatile char usmStr_{$prop['altname']}[70]");
                        array_push($stringcmps, "\t\tcall 'usmStrCheck' ( $numDevices, $numProps, {$prop['altname']} )");
                        break;
                }

                array_push($structure, "		usmDev[$numDevices].property[$numProps].name       = '{$prop['name']}'
        usmDev[$numDevices].property[$numProps].newVal     = '{$prop['value']}'
		usmDev[$numDevices].property[$numProps].type       = $type
		usmDev[$numDevices].property[$numProps].channel    = '{$prop['altname']}'
		usmDev[$numDevices].property[$numProps].usmType    = '{$prop['type']}'
		usmDev[$numDevices].property[$numProps].alertCfg   = '{$prop['alert_config']}'
		usmDev[$numDevices].property[$numProps].alertVal   = '{$prop['alert_value']}'
		usmDev[$numDevices].property[$numProps].alertType  = {$prop['alert_type']}
		usmDev[$numDevices].property[$numProps].prefix     = '{$prop['prefix']}'
		usmDev[$numDevices].property[$numProps].suffix     = '{$prop['suffix']}'
		usmDev[$numDevices].property[$numProps].capitalize = '{$prop['capitalize']}'");

                $hashes = array();
                $numTranslations = 0;
                $translations = getPropertyTranslationsCG($connection, $prop['id']);

                foreach($translations as $tran) {
                    $numTranslations++;

                    array_push($hashes, "			usmDev[$numDevices].property[$numProps].hash[$numTranslations].name  = '{$tran['name']}'
			usmDev[$numDevices].property[$numProps].hash[$numTranslations].value = '{$tran['translation']}'");
                }

                array_unshift($hashes, "		usmDev[$numDevices].property[$numProps].hashCount  = $numTranslations");
                $hashes = join("\n", $hashes);

                array_push($structure, $hashes);
                array_push($structure, "");
            }

            array_unshift($structure, "	usmDev[$numDevices].name          = '{$device['caption']}'
	usmDev[$numDevices].device        = {$device['name']}
	usmDev[$numDevices].propertyCount = $numProps\n");

            $structure = join("\n", $structure);
            array_push($structures, $structure);
		}

        $file = 'usmCG.template';

        $version = 'v1.07php';
        $server = $_SERVER['HTTP_HOST'];
        
        $constants = "\tinteger usmDevCount         = $numDevices

    char    usmConstCampus[]    = '$campus'
    char    usmConstBuilding[]  = '$building'
    char    usmConstRoom[]      = '$room'\n";

        $variables = join("\n", $variables);
        $stringcmps = join("\n", $stringcmps);
        $structures = join("\n", $structures);
        $events = join("\n", $events);

        $search = array('$$$version', '$$$server', '$$$constants', '$$$variables', '$$$structures', '$$$events', '$$$StringComparisons');
        $replace = array($version, $server, $constants, $variables, $structures, $events, $stringcmps);

        $generator = file_get_contents($file);
        $generator = str_replace($search, $replace, $generator);

        header('Content-Disposition: attachment; filename="USM.inc"');
        header('Content-Length: ' . strlen($generator));
        flush();

        echo $generator;
    }
?>