<?php
    function parseDate( $date ) {
        $date = strptime( $date, "%Y%m%d%H%M%S" );
        $year = $date['tm_year']+1900;
        $month = $date['tm_mon']+1;
        $day = $date['tm_mday'];
        $hour = $date['tm_hour'];
        $minute = $date['tm_min'];
        $second = $date['tm_sec'];
	return strtotime( "$year-$month-$day $hour:$minute:$second" );
    }

    function getTemp( $date ) {
	$temp = 'n/a';

        mysql_connect( '127.0.0.1', 'homerseklet', '' );
	if( !@mysql_select_db( 'homerseklet' ) )
	    return $temp;

	$result = mysql_query( "select `date`, `value` from `kint` where unix_timestamp(`date`) < $date order by `date` desc limit 1" );
        if( $result ) {
            $result = mysql_fetch_row( $result );
            if( strtotime($result[0]) - time() <= 600 ) // max 10 minute difference allowed
		$temp = $result[1];
	}
        mysql_close();
        return $temp;
    }

    function addOverlay( $imgFile, $overlayFile, $interlace ) {
	$imgFileExploded = explode( '-', $imgFile );
	$date = parseDate( $imgFileExploded[1] );
	$temp = getTemp( $date );

	$overlayImage = imagecreatefrompng( $overlayFile );
	$webcamImage = imagecreatefromjpeg( $imgFile );
	$width = imagesx( $webcamImage );
	$height = imagesy( $webcamImage );

	imagecopy( $webcamImage, $overlayImage, 0, 0, 0, 0, $width, $height );
	imagedestroy( $overlayImage );
	$fontColor = imagecolorallocate( $webcamImage, 255, 255, 255 );
	$fontColorShadow = imagecolorallocate( $webcamImage, 0, 0, 0 );
	$fontFile = substr(__FILE__, 0, strrpos(__FILE__, '/')) . '/font.ttf';
	if( $date )
	    $dateText = date( 'Y-m-d H:i:s', $date ) . ' (UTC+' . (date('Z')/3600) . ')';
	else
	    $dateText = 'n/a';
	imagefttext( $webcamImage, 10.5, 0, 402, $height-11, $fontColorShadow, $fontFile, $dateText );
	imagefttext( $webcamImage, 10.5, 0, 401, $height-12, $fontColor, $fontFile, $dateText );
	imagefttext( $webcamImage, 10.5, 0, 613, $height-11, $fontColorShadow, $fontFile, "${temp}°C" );
	imagefttext( $webcamImage, 10.5, 0, 612, $height-12, $fontColor, $fontFile, "${temp}°C" );
	if( $interlace )
    	    imageinterlace( $webcamImage, 1 );
	return $webcamImage;
    }
?>
