chiark / gitweb /
Copyright notices
[ypp-sc-tools.db-live.git] / yarrg / web / lookup
1 %# This is part of the YARRG website.  YARRG is a tool and website
2 %# for assisting players of Yohoho Puzzle Pirates.
3 %#
4 %# Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
5 %# Copyright (C) 2009 Clare Boothby
6 %#
7 %#  YARRG's client code etc. is covered by the ordinary GNU GPL (v3 or later).
8 %#  The YARRG website is covered by the GNU Affero GPL v3 or later, which
9 %#   basically means that every installation of the website will let you
10 %#   download the source.
11 %#
12 %# This program is free software: you can redistribute it and/or modify
13 %# it under the terms of the GNU Affero General Public License as
14 %# published by the Free Software Foundation, either version 3 of the
15 %# License, or (at your option) any later version.
16 %#
17 %# This program is distributed in the hope that it will be useful,
18 %# but WITHOUT ANY WARRANTY; without even the implied warranty of
19 %# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 %# GNU Affero General Public License for more details.
21 %#
22 %# You should have received a copy of the GNU Affero General Public License
23 %# along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 %#
25 %# Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
26 %# are used without permission.  This program is not endorsed or
27 %# sponsored by Three Rings.
28 %#
29 %#
30 %# This Mason component generates the main `lookup' page, including
31 %# all the entry boxes etc. for every query.
32 %#
33 <%perl>
34 my %a;
35 my %ahtml;
36 my @vars;
37
38 # for output:
39 my @archipelagoes;
40 my @islandids;
41 my %islandid2;
42
43 #---------- "mode" argument parsing and mode menu at top of page ----------
44
45 # for debugging, invoke as
46 #  http://www.chiark.greenend.org.uk/ucgi/~clareb/mason/pirates/pirate-route?debug=1
47
48 @vars= ({       Name => 'Ocean',
49                 Before => 'Ocean: ',
50                 CmpCanon => sub { ucfirst lc $_[0] },
51                 Values => [ ocean_list() ]
52         }, {    Name => 'Dropdowns',
53                 Before => 'Interface: ',
54                 CmpCanon => sub { !!$_[0] },
55                 Values => [     [ 0, 'Type in names' ],
56                                 [ 4, 'Select from menus' ] ]
57         }, {    Name => 'Query',
58                 Before => 'Query: ',
59                 Values => [     [ 'route', 'Trades for route' ],
60                                 [ 'age', 'Data age' ] ]
61         });
62
63 foreach my $var (@vars) {
64         my $name= $var->{Name};
65         my $lname= lc $name;
66         $var->{Before}= '' unless exists $var->{Before};
67         $var->{CmpCanon}= sub { $_[0]; } unless exists $var->{CmpCanon};
68         foreach my $val (@{ $var->{Values} }) {
69                 next if ref $val;
70                 $val= [ $val, encode_entities($val) ];
71         }
72         if (exists $ARGS{$lname}) {
73                 $a{$name}= $ARGS{$lname};
74                 my @html= grep { $_->[0] eq $a{$name} } @{ $var->{Values} };
75                 $ahtml{$name}= @html==1 ? $html[0][1] : '???';
76         } else {
77                 $a{$name}= $var->{Values}[0][0];
78                 $ahtml{$name}= $var->{Values}[0][1];
79         }
80 }
81
82 </%perl>
83 <html><head><title><% ucfirst $ahtml{Query} %> - YARRG</title></head><body>
84
85 <a href="<% $m->current_comp()->name() |u %>">YARRG</a> -
86  Yet Another Revenue Research Gatherer
87 <p>
88 <%perl>
89
90 my %baseqf;
91 foreach my $var (@vars) {
92         my $lname= lc $var->{Name};
93         next unless exists $ARGS{$lname};
94         $baseqf{$lname}= $ARGS{$lname};
95 }
96
97 my %queryqf;
98 foreach my $var (keys %ARGS) {
99         next unless $var =~
100                 m/^(?:routestring|islandid\d|archipelago\d|debug)$/;
101         my $val= $ARGS{$var};
102         next if $val eq 'none';
103         $queryqf{$var}= $val;
104 }
105
106 my $quri= sub {
107         my $uri= URI->new('lookup');
108         $uri->query_form(@_);
109         $uri->path_query();
110 };
111
112 foreach my $var (@vars) {
113         my $name= $var->{Name};
114         my $lname= lc $var->{Name};
115         my $delim= $var->{Before};
116         my $canon= &{$var->{CmpCanon}}($a{$name});
117         my $cvalix= 0;
118         foreach my $valr (@{ $var->{Values} }) {
119                 print $delim;  $delim= "\n|\n";
120                 my ($value,$html) = @$valr;
121                 my $iscurrent= &{$var->{CmpCanon}}($value) eq $canon;
122                 my $after;
123                 if ($iscurrent) {
124                         print '<b>';
125                         $after= '</b>';
126                 } else {
127                         my %qf= (%baseqf,%queryqf);
128                         delete $qf{$lname};
129                         $qf{$lname}= $value if $cvalix;
130                         print '<a href="',$quri->(%qf),'">';
131                         $after= '</a>';
132                 }
133                 print $html, $after;
134                 $cvalix++;
135         }
136         print "<p>\n\n";
137 }
138
139 #---------- initial checks, startup, main entry form ----------
140
141 dbw_connect($a{Ocean});
142
143 </%perl>
144 <%args>
145 $debug => 0
146 $routestring => ''
147 </%args>
148
149 <hr>
150
151 %########### query `route' ##########
152 % if ($a{Query} eq 'route') {
153
154 <h1>Specify route</h1>
155 <form action="<% $quri->() %>" method="get">
156
157 %#---------- textbox, user enters route as string ----------
158 % if (!$a{Dropdowns}) {
159
160 Enter route (islands, or archipelagoes, separated by |s or commas;
161  abbreviations are OK):<br/>
162
163 <script type="text/javascript">
164 tr_uri= "routetextstring?format=json&type=text/xml"
165                 + "&ocean=<% uri_escape($a{Ocean}) %>";
166
167 tr_timeout=false;
168 tr_request=false;
169 tr_done='';
170 tr_needed='';
171 function tr_Later(){
172   window.clearTimeout(tr_timeout);
173   tr_timeout = window.setTimeout(tr_Needed, 500);
174 }
175 function tr_Needed(){
176   window.clearTimeout(tr_timeout);
177   tr_element= document.getElementById('routestring');
178   tr_needed= tr_element.value;
179   tr_Request();
180 }
181 function tr_Request(){
182   if (tr_request || tr_needed==tr_done) return;
183   tr_done= tr_needed;
184   tr_request= new XMLHttpRequest();
185   uri= tr_uri+'&string='+encodeURIComponent(tr_needed);
186   tr_request.open('GET', uri);
187   tr_request.onreadystatechange= tr_Ready;
188   tr_request.send(null);
189 }
190 function tr_Ready() {
191   if (tr_request.readyState != 4) return;
192   if (tr_request.status == 200) {
193     response= tr_request.responseText;
194     eval('results='+response);
195     toedit= document.getElementById('routeresults');
196     toedit.innerHTML= results.show;
197   }
198   tr_request= false;
199   tr_Request();
200 }
201 window.onload= tr_Needed;
202 </script>
203
204 <input type="text" id="routestring" name="routestring" size=80
205  value="<% $routestring |h %>"
206  onchange="tr_Needed();"
207  onkeyup="tr_Later();"><br>
208 <div id="routeresults">&nbsp;</div><br/>
209
210 % } else { #---------- dropdowns, user selects from menus ----------
211
212 <%perl>
213 my ($sth,$row);;
214 my @archlistdata;
215 my %islandlistdata;
216 $islandlistdata{'none'}= [ [ "none", "Select island..." ] ];
217
218 my $optionlistmap= sub {
219         my ($optlist, $selected) = @_;
220         my $out='';
221         foreach my $entry (@$optlist) {
222                 $out.= sprintf('<option value="%s" %s>%s</option>',
223                         encode_entities($entry->[0]),
224                         defined $selected && $entry->[0] eq $selected
225                                 ? 'selected' : '',
226                         encode_entities($entry->[1]));
227         }
228         return $out;
229 };
230
231 my $dbh= dbw_connect($a{Ocean});
232
233 $sth= $dbh->prepare("SELECT DISTINCT archipelago FROM islands
234                             ORDER BY archipelago;");
235 $sth->execute();
236
237 while ($row=$sth->fetchrow_arrayref) {
238         my ($arch)= @$row;
239         push @archlistdata, [ $arch, $arch ];
240         $islandlistdata{$arch}= [ [ "none", "Whole arch" ] ];
241 }
242
243 $sth= $dbh->prepare("SELECT islandid,islandname,archipelago
244                             FROM islands
245                             ORDER BY islandname;");
246 $sth->execute();
247
248 while ($row=$sth->fetchrow_arrayref) {
249         my $arch= $row->[2];
250         push @{ $islandlistdata{'none'} }, [ @$row ];
251         push @{ $islandlistdata{$arch} }, [ @$row ];
252         $islandid2{$row->[0]}= { Name => $row->[1], Arch => $arch };
253 }
254
255 my %resetislandlistdata;
256 foreach my $arch (keys %islandlistdata) {
257         $resetislandlistdata{$arch}=
258                 $optionlistmap->($islandlistdata{$arch}, '');
259 }
260
261 </%perl>
262
263 <input type=hidden name=dropdowns value="<% $a{Dropdowns} |h %>">
264
265 <script type="text/javascript">
266 ms_lists= <% to_json(\%resetislandlistdata) %>;
267 function ms_Setarch(dd) {
268   debug('ms_SetArch '+dd+' arch='+arch);
269   var arch= document.getElementsByName('archipelago'+dd).item(0).value;
270   var got= ms_lists[arch];
271   if (got == undefined) return; // unknown arch ?  hrm
272   debug('ms_SetArch '+dd+' arch='+arch+' got ok');
273   var select= document.getElementsByName('islandid'+dd).item(0);
274   select.innerHTML= got;
275   debug('ms_SetArch '+dd+' arch='+arch+' innerHTML set');
276 }
277 </script>
278
279 <table style="table-layout:fixed; width:90%;">
280
281 <tr>
282 %       for my $dd (0..$a{Dropdowns}-1) {
283 <td>
284 <select name="archipelago<% $dd %>" onchange="ms_Setarch(<% $dd %>)">
285 <option value="none">Whole ocean</option>
286 <% $optionlistmap->(\@archlistdata, $ARGS{"archipelago$dd"}) %></select></td>
287 %       }
288 </tr>
289
290 <tr>
291 %       for my $dd (0..$a{Dropdowns}-1) {
292 %               my $arch= $ARGS{"archipelago$dd"};
293 %               $arch= 'none' if !defined $arch;
294 <td>
295 <select name="islandid<% $dd %>">
296 <% $optionlistmap->($islandlistdata{$arch}, $ARGS{"islandid$dd"}) %>
297 </select></td>
298 %       }
299 </tr>
300
301 </table>
302
303 % } #---------- end of dropdowns, now common middle of page code ----------
304
305 <input type=submit name=submit value="Go">
306 </form>
307
308 <%perl>
309 #========== result computations ==========
310
311 my $results_head;
312 $results_head= sub {
313         print "<h1>Results</h1>\n";
314         $results_head= sub { };
315 };
316
317 #---------- result computation - textstring ----------
318 if (!$a{Dropdowns}) {
319   if (length $routestring) {
320         $results_head->();
321         my $rsr= $m->comp('routetextstring',
322                 ocean => $a{Ocean},
323                 string => $routestring,
324                 format => 'return'
325         );
326         if (length $rsr->{Error}) {
327                 print encode_entities($rsr->{Error});
328         } else {
329                 foreach my $entry (@{ $rsr->{Results} }) {
330                         push @archipelagoes,
331                                 defined $entry->[1] ? undef : $entry->[0];
332                         push @islandids, $entry->[1];
333                 } 
334         }
335   }
336
337 } else { #---------- results - dropdowns ----------
338
339 my $argorundef= sub {
340         my ($dd,$base) = @_;
341         my $thing= $ARGS{"${base}${dd}"};
342         $thing= undef if defined $thing and $thing eq 'none';
343         return $thing;
344 };
345
346 for my $dd (0..$a{Dropdowns}-1) {
347         my $arch= $argorundef->($dd,'archipelago');
348         my $island= $argorundef->($dd,'islandid');
349         next unless defined $arch or defined $island;
350         if (defined $island and defined $arch) {
351                 my $ii= $islandid2{$island};
352                 my $iarch= $ii->{Arch};
353                 if ($iarch ne $arch) {
354                         $results_head->();
355 </%perl>
356  Specified archipelago <% $arch %> but
357  island <% $ii->{Name} %>
358  which is in <% $iarch %>; using the island.<br>
359 <%perl>
360                 }
361                 $arch= undef;
362         }
363         push @archipelagoes, $arch;
364         push @islandids, $island;
365 }
366
367 }#---------- result processing, common stuff
368 </%perl>
369
370 % if (@islandids) {
371 %       $results_head->();
372
373 <& routetrade, islandids => \@islandids, archipelagoes => \@archipelagoes &>
374
375 % }
376
377 % } elsif ($a{Query} eq 'age') {
378 % ########### query `age' ##########
379
380 <h1>Market data age</h1>
381 <& dataage, %baseqf, %queryqf &>
382
383 % } ########## end of `age' query ##########
384
385 %#---------- debugging and epilogue ----------
386
387 % if ($debug) {
388 <p>
389 <pre id="debug_log">
390 Debug log:
391 </pre>
392 % }
393
394 <script type="text/javascript">
395 function debug (m) {
396 % if ($debug) {
397   var node= document.getElementById('debug_log');
398   node.innerHTML += "\n" + m + "\n";
399 % }
400 }
401 </script>
402
403 <& footer &>
404
405 <%init>
406 use CommodsWeb;
407 use HTML::Entities;
408 use URI::Escape;
409 use JSON;
410
411 </%init>