#!/usr/bin/perl
# Merge the cvs data and the XLSX (will not work for XLS)
use File::Slurper 'read_text','write_text';

my $template="Floorplan_offices-mod.xlsx";
my $data="roomtags.csv";
my $outputdir="output";
my $temp="tempfloorplan";
#---------------------------
my $work="$temp/xl/sharedStrings.xml";

MAIN: {
	#check and prep what we need..
	die("can not find $data") if (! -e "$data");
	die("can not find $template") if (! -e "$template");

	open(INFO,"$data") or die ("Soemethingwong with $data");
	$headers=<INFO>;
	chomp($headers); chomp($headers);

	#Get the tab separate columnames from the first line 
	my(@headers)=split("\t",$headers);

	#This will hold all labels
	my(%tags);

	#for the each room (line)
	foreach(<INFO>) {
		my(%data);
		#Cleanup
		chomp($_); chomp($_);
		s/&/&amp;/g; s/</&lt;/g; s/>/&gt;/g;
		@data=split("\t",$_);
		#Map it to %data
		@data{@headers}=@data;
		$newheaders=$headers;
		$newheaders=~s/LBL_UNIQNAME_/$data{KAMR}_L_N/g;
		$newheaders=~s/LBL_UNIQNAME_/$data{KAMR}R_L_N/g;
		@tags{split("\t",$newheaders)}=@data;
	}

	#Prepare template
	`rm $temp -Rf; mkdir $temp; unzip $template -d$temp`;
	my $file=read_text("$work");

	#Replace things that need replacing
	$file =~ s/$_/$tags{$_}/g foreach(sort(keys(%tags)));

	#Erase all the remaing tags (Rooms with no info in prinsys)
	$file =~ s/[AB]\d\.*\d*\d*R*_L_N0\d//g;

	#Update the fie on disk
	write_text("$work",$file);

	#finish floorplan
	`(cd $temp && zip -r ../$outputdir/Floorplan-auto.xlsx *)`;
	close(DATA);
	#cleanup
	`rm $temp -Rf`;
}
