%RWS_SUPPLETIEDATABASE2KMZ   plots rijkswaterstaat suppleties in google earth
% Generates .kml and .kmz files
% rws_suppletiedatabase.kml file points to on-line images.
% rws_suppletiedatabase.kmz file can run off-line. 
%
%See also: rws_suppletiedatabase

FileName = 'rws_suppletiedatabase.kml';

%% get and write nourishement data

D = rws_suppletiedatabase();

%% start .kml file

OPT.fid                 = fopen(FileName,'w');

OPT.types               = {'strandsuppletie' 'onderwatersuppletie' 'zeewaartse_duinverzwaring' 'landwaartse_duinverzwaring' 'otherwise'};

OPT.iconnormalState     = 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png';%'http://svn.openlaszlo.org/sandbox/ben/smush/circle-white.png';
OPT.iconhighlightState  = 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png';%'http://svn.openlaszlo.org/sandbox/ben/smush/circle-white.png';

OPT.iconnormalState     = 'http://google-maps-icons.googlecode.com/files/water.png'; % onderwater
OPT.iconhighlightState  = 'http://google-maps-icons.googlecode.com/files/water.png';

OPT.iconnormalState     = 'http://google-maps-icons.googlecode.com/files/beach.png'; % strandsuppletie
OPT.iconhighlightState  = 'http://google-maps-icons.googlecode.com/files/beach.png';

OPT.iconnormalState     = 'http://google-maps-icons.googlecode.com/files/landfill2.png'; % duinverzwaring
OPT.iconhighlightState  = 'http://google-maps-icons.googlecode.com/files/landfill2.png';

OPT.iconnormalState     = 'http://google-maps-icons.googlecode.com/files/friends.png'; % otherwise
OPT.iconhighlightState  = 'http://google-maps-icons.googlecode.com/files/friends.png';

OPT.scalenormalState    = 0.8;
OPT.scalehighlightState = 1.2;

OPT.fillColor_strandsuppletie            = [1 0 0];
OPT.fillColor_onderwatersuppletie        = [0 1 0];
OPT.fillColor_zeewaartse_duinverzwaring  = [1 0 1];
OPT.fillColor_landwaartse_duinverzwaring = [1 1 0];
OPT.fillColor_otherwise                  = [0 1 1];

%% HEADER
OPT_header = struct(...
    'name'       ,'Nourishments',...
    'open'       ,1,...
    'description','Nourishments',...
    'lon',5,'lat',52.5,'z',300e3,'timeIn' ,datestr(min(D.datenum0),'yyyy'),...
                               'timeOut',datestr(max(D.datenum1),'yyyy'));
    
output = KML_header(OPT_header);

%% STYLE for patches

output = [output KML_stylePoly('name','patch_strandsuppletie'           ,'lineAlpha',0.,'fillAlpha',.3,'fillColor',OPT.fillColor_strandsuppletie           )];
output = [output KML_stylePoly('name','patch_onderwatersuppletie'       ,'lineAlpha',0.,'fillAlpha',.3,'fillColor',OPT.fillColor_onderwatersuppletie       )];
output = [output KML_stylePoly('name','patch_zeewaartse_duinverzwaring' ,'lineAlpha',0.,'fillAlpha',.3,'fillColor',OPT.fillColor_zeewaartse_duinverzwaring )];
output = [output KML_stylePoly('name','patch_landwaartse_duinverzwaring','lineAlpha',0.,'fillAlpha',.3,'fillColor',OPT.fillColor_landwaartse_duinverzwaring)];
output = [output KML_stylePoly('name','patch_otherwise'                 ,'lineAlpha',0.,'fillAlpha',.3,'fillColor',OPT.fillColor_otherwise                 )];

output = [output KML_stylePoly('name','line_strandsuppletie'            ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',OPT.fillColor_strandsuppletie           )];
output = [output KML_stylePoly('name','line_onderwatersuppletie'        ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',OPT.fillColor_onderwatersuppletie       )];
output = [output KML_stylePoly('name','line_zeewaartse_duinverzwaring'  ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',OPT.fillColor_zeewaartse_duinverzwaring )];
output = [output KML_stylePoly('name','line_landwaartse_duinverzwaring' ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',OPT.fillColor_landwaartse_duinverzwaring)];
output = [output KML_stylePoly('name','line_otherwise'                  ,'lineAlpha',.5,'fillAlpha',.3,'fillColor',OPT.fillColor_otherwise                 )];

%% STYLE for pushpin

for j = 1:length(OPT.types)
    switch OPT.types{j}
        case 'strandsuppletie'
            OPT.iconnormalState     = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_beach_waves.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-ff0000/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/beach_waves.png';
            OPT.iconhighlightState  = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_beach_waves.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-ff0000/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/beach_waves.png';
        case 'onderwatersuppletie'
            OPT.iconnormalState     = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_lake.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-00ff00/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/lake.png';
            OPT.iconhighlightState  = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_lake.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-00ff00/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/lake.png';
        case 'zeewaartse_duinverzwaring'
            OPT.iconnormalState     = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_z_peak.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-ff00ff/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/peak.png';
            OPT.iconhighlightState  = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_z_peak.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-ff00ff/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/peak.png';
        case 'landwaartse_duinverzwaring'
            OPT.iconnormalState     = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_l_peak.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-ffff00/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/peak.png';
            OPT.iconhighlightState  = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_l_peak.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-ffff00/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/peak.png';
        case 'otherwise'
            OPT.iconnormalState     = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_information.png';%'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-00ffff/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/information.png';
            OPT.iconhighlightState  = 'http://kml.deltares.nl/kml/rijkswaterstaat/suppleties/icons/nicolasmollet_information.png'; %'http://mapicons.nicolasmollet.com/wp-content/uploads/mapicons/shape-default/color-00ffff/shapecolor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshadowstyle-dark/gradient-iphone/information.png';            
    end
    
urlwrite(OPT.iconnormalState    ,filenameext(OPT.iconnormalState)  );
urlwrite(OPT.iconhighlightState,filenameext(OPT.iconhighlightState));

output = [output ...
    '<StyleMap id="pushpin_' OPT.types{j} '">\n'...
    ' <Pair><key>normal</key><styleUrl>#pushpin_normal_' OPT.types{j} '</styleUrl></Pair>\n'...
    ' <Pair><key>highlight</key><styleUrl>#pushpin_highlight_' OPT.types{j} '</styleUrl></Pair>\n'...
    '</StyleMap>\n'...
    '<Style id="pushpin_normal_' OPT.types{j} '">\n'...
    ' <IconStyle>\n'...
    ' <scale>' num2str(OPT.scalenormalState) '</scale>\n'...
    ' <Icon><href>' filenameext(OPT.iconnormalState) '</href></Icon>\n'...
    ' </IconStyle>\n'...
    ' <LabelStyle><color>000000ff</color><scale>0</scale></LabelStyle>\n'... % no text except when mouse hoover
    ' </Style>\n'...
    '<Style id="pushpin_highlight_' OPT.types{j} '">\n'...
    ' <BalloonStyle><text>\n'...
    ' <h3>$[name]</h3>'... % variable per dot
    ' $[description]\n'... % variable per dot
    ' </text></BalloonStyle>\n'...
    ' <IconStyle>\n'...
    ' <scale>' num2str(OPT.scalehighlightState) '</scale>\n'...
    ' <Icon><href>' filenameext(OPT.iconhighlightState) '</href></Icon>\n'...
    ' </IconStyle>\n'...
    ' <LabelStyle></LabelStyle>\n'...
    ' </Style>\n'];

fprintf(OPT.fid,output);output = [];

end

for i=1:length(D.areacode);
    
if (D.b_gemeten(i)==0) | isnan(D.b_gemeten(i)) | isnan(D.l_beginraai(i)) | isnan(D.l_lengteraai(i))

   disp(['skipping   ',num2str(i,'%0.4d'),'/',num2str(length(D.areacode),'%0.4d')])

else

   disp(['processing ',num2str(i,'%0.4d'),'/',num2str(length(D.areacode),'%0.4d')])

    x=[D.x_beginraai(i);D.x_eindraai(i)]; % x_begin x_end
    y=[D.y_beginraai(i);D.y_eindraai(i)]; % y_begin y_end 
    switch D.b_typewerk{i} % type
        case 'strandsuppletie'
        offset1 = 0;
        offset2 = D.b_gemeten_per_m(i);
        PolyStyleName = 'strandsuppletie';
        OPT.fillColor = OPT.fillColor_strandsuppletie;
        case 'onderwatersuppletie'
        offset1 = 400;
        offset2 = D.b_gemeten_per_m(i)+400;
        PolyStyleName = 'onderwatersuppletie';
        OPT.fillColor = OPT.fillColor_onderwatersuppletie;
        case 'zeewaartse duinverzwaring'
        offset1 = -D.b_gemeten_per_m(i)-30;
        offset2 = -30;
        PolyStyleName = 'zeewaartse_duinverzwaring';
        OPT.fillColor = OPT.fillColor_zeewaartse_duinverzwaring;
        case 'landwaartse duinverzwaring'
        offset1 = -D.b_gemeten_per_m(i)-100;
        offset2 = -100;
        PolyStyleName = 'landwaartse_duinverzwaring';
        OPT.fillColor = OPT.fillColor_landwaartse_duinverzwaring;
        otherwise
        offset1 = 0;
        offset2 = D.b_gemeten_per_m(i);
        PolyStyleName = 'otherwise';
        OPT.fillColor = OPT.fillColor_otherwise;
    end
    
    %% change signs for wadden island (joost may know why)
    
    if D.areacode(i)<7
        ofsset1=-offset1;
        offset2=-offset2;
    end
    
    
    x(3:4)=     x+(y(2)-y(1))*offset2/sqrt((x(2)-x(1))^2+(y(2)-y(1))^2);
    y(3:4)=     y-(x(2)-x(1))*offset2/sqrt((x(2)-x(1))^2+(y(2)-y(1))^2);
    x(1:2)=x(1:2)+(y(2)-y(1))*offset1/sqrt((x(2)-x(1))^2+(y(2)-y(1))^2);
    y(1:2)=y(1:2)-(x(2)-x(1))*offset1/sqrt((x(2)-x(1))^2+(y(2)-y(1))^2);
    x=x([1, 2, 4, 3, 1]);
    y=y([1, 2, 4, 3, 1]);
    [lon, lat]=convertCoordinates(x,y,'CS1.code',28992,'CS2.code',4326);
    
    %% add KML element for suppletie
    
    t0    =  datestr(D.datenum0(i),'yyyy');
    t1    =  datestr(D.datenum1(i),'yyyy');
    name1 = [datestr(D.datenum0(i),'yyyy-mmm'),' - ',datestr(D.datenum0(i),'yyyy-mmm')];
    if D.n_code(i) ==0
    name2 = [D.b_typewerk{i},' (planned)'];
    else
    name2 = [D.b_typewerk{i},' (code ',num2str(D.n_code(i)),')'];
    end
    name3 = [num2str(D.b_gemeten(i)),' m^3'];
    
    temp      = dec2hex(round(OPT.fillColor.*255),2); % define cell color
    fillColor = [temp(1,:) temp(2,:) temp(3,:)];
    
    html  = ['<hr>'...
             '<br><A href = "http://www.rijkswaterstaat.nl">Rijkswaterstaat</A> suppletie data.'...
             '<br><br> '...
             '<table border="1"> <tr>\n',...
             '<td>type   </td><td bgcolor="',fillColor,'">',D.b_typewerk{i},'</td></tr>\n',...
             '<td>tijdvak</td><td>(',datestr(D.datenum0(i),'yyyy-mmm'),' - ',datestr(D.datenum0(i),'yyyy-mmm'),')','</td></tr>\n',...
             '<td>volume </td><td>',num2str(D.b_gemeten(i)),' m^3','</td></tr>\n',...
             '<td>volume per strekende meter</td><td>',num2str(D.b_gemeten_per_m(i)),' m^3/m','</td></tr>\n',...
             '<td>kustvak</td><td>',num2str(D.areacode(i)),' = ',D.Kustvak{i},' </td></tr>\n',...
             '<td>x</td><td>',num2str(D.x_beginraai(i)),' - ',num2str(D.x_eindraai(i)),' m</td></tr>\n',...
             '<td>y</td><td>',num2str(D.y_beginraai(i)),' - ',num2str(D.y_eindraai(i)),' m</td></tr>\n',...
             '</table>',...
             '<br>Provided by:',...
             '<img src="https://public.deltares.nl/download/attachments/16876019/OET?version=2" align="right" width="100"/>'];
    
    output = [output '<Folder>'];
    output = [output '<name>' name1 '</name>'];
    output = [output '<open>1</open>'];
    output = [output   KML_poly(lat,lon,'clampToGround','name',name2,'styleName',['patch_',PolyStyleName],'timeIn',t0,'timeOut',t1)];
    output = [output '<Folder>'];
    output = [output '<name>' name3 '</name>'];
    output = [output '<open>0</open>'];
    output = [output   KML_line(lat,lon,'clampToGround','name','outline','styleName',['line_' ,PolyStyleName],'timeIn',t0,'timeOut',t1)];
    output = [output ...
             ' <Placemark>'...
             ' <TimeSpan>\n'...
             ' <begin>',t0,'</begin>\n'...          % t0
             ' <end>',t1,'</end>\n'...              % t1
             ' </TimeSpan>\n'...
             ' <name>',name2,'</name>\n'...          % name
             ' <description><![CDATA['...           % start required wrapper for html
              html,...                              % description
              ']]></description>\n'...              % end   required wrapper for html
             ' <styleUrl>#pushpin_' PolyStyleName '</styleUrl>\n'...  % styleName
             ' <Point><coordinates>',num2str(lon(3)),',',num2str(lat(3)),',0</coordinates></Point>\n'...
             ' </Placemark>'];
    output = [output '</Folder>'];
    output = [output '</Folder>'];
    
end % volume=0
end % loop

    fprintf(OPT.fid,output);

%% FOOTER

output = [KML_footer];
fprintf(OPT.fid,output);

%% close KML

fclose(OPT.fid);

%% make kmz 
% to work off-line on Google-Earth
zipfile = cell(1,5);
for j = 1:length(OPT.types)
    switch OPT.types{j}
        case 'strandsuppletie'
            OPT.iconnormalState     = '\icons\nicolasmollet_beach_waves.png';
            OPT.iconhighlightState  = '\icons\nicolasmollet_beach_waves.png';
            zipfile{j} = unique(vertcat(filenameext(OPT.iconnormalState), filenameext(OPT.iconhighlightState)), 'rows');
        case 'onderwatersuppletie'
            OPT.iconnormalState     = '\icons\nicolasmollet_lake.png';
            OPT.iconhighlightState  = '\icons\nicolasmollet_lake.png';
            zipfile{j} = unique(vertcat(filenameext(OPT.iconnormalState), filenameext(OPT.iconhighlightState)), 'rows');
        case 'zeewaartse_duinverzwaring'
            OPT.iconnormalState     = '\icons\nicolasmollet_z_peak.png';
            OPT.iconhighlightState  = '\icons\nicolasmollet_z_peak.png';
            zipfile{j} = unique(vertcat(filenameext(OPT.iconnormalState), filenameext(OPT.iconhighlightState)), 'rows');
        case 'landwaartse_duinverzwaring'
            OPT.iconnormalState     = '\icons\nicolasmollet_l_peak.png';
            OPT.iconhighlightState  = '\icons\nicolasmollet_l_peak.png';
            zipfile{j} = unique(vertcat(filenameext(OPT.iconnormalState), filenameext(OPT.iconhighlightState)), 'rows');
        case 'otherwise'
            OPT.iconnormalState     = '\icons\nicolasmollet_information.png';
            OPT.iconhighlightState  = '\icons\nicolasmollet_information.png';            
            zipfile{j} = unique(vertcat(filenameext(OPT.iconnormalState), filenameext(OPT.iconhighlightState)), 'rows');
    end
    
end

KML2kmz(filename(FileName),'.kml',{FileName,zipfile{:}})

%zip    ([filename(FileName),'.zip'],{FileName,zipfile{:}})
%delete (zipfile{:})
%copyfile([filename(FileName),'.zip'],[filename(FileName),'.kmz'])
%delete ([filename(FileName),'.kml'])
%delete ([filename(FileName),'.zip'])
