[% content_only = 1 # no html wrappers %]

<!-- BEGIN record/body.tt -->
  [%
	data = request.data; # PROCESS dumper.tt dump = data.request_trial.as_tree;

	patient = data.patient_case.patient;
	history = request.history;

	is_amended_report = request.previous_diagnoses.size
	  || data.request_report.comment.match('additional comment')
		? 1 : 0; # maybe revised in result summary section
  %]

	[% report_tt = c.cfg('settings').local_report_tt; # PROCESS dumper.tt dump = report_tt %]

[% IF c.cfg('settings').local_report_tt; # won't be HMDS
    report_tmpl = c.cfg('settings').item('_centre'); # expects filename = centre in record/local
	PROCESS "record/local/${report_tmpl}.tt";
	ELSE %]
  [%
	footer =
	  c.cfg('settings').lab_name_abbreviation _ ', ' _
	  c.cfg('settings').service_address _ ' Tel. ' _
	  c.cfg('settings').service_telno
  %]
  <!-- FOOTER CENTER "[% footer %]" -->

	[% # PROCESS dumper.tt dump = request.raw_lab_test_data.result_summaries %]
	[% # PROCESS dumper.tt dump = context_warning_map %]
	[% # PROCESS dumper.tt dump = nhs_number_exempt %]
	[% # PROCESS dumper.tt dump = report_error_codes %]
    [% # PROCESS dumper.tt dump = dispatch_log %]
    [% # PROCESS dumper.tt dump = request %]
	[% # PROCESS dumper.tt dump = request.result_summaries %]
    [% # PROCESS dumper.tt dump = request.previous_diagnoses %]
	[% # PROCESS dumper.tt dump = request.special_formatting %]
	[% # PROCESS dumper.tt dump = request.specimen_map.item(data.id) %]
	[% # PROCESS dumper.tt dump = request.outstanding_tests %]

	[% # FOREACH foo IN request.all_results;
	   # PROCESS dumper.tt dump = foo.as_tree; END %]

  [% UNLESS active_link.match('printrun') # printrun gets its own back_button %]
	<p class="classname">[% site.html.back_button %]</p>
  [% END %]

  <center>
    <p>
      <font color="blue" size="+3">
        [% c.cfg('settings').service_name %]
      </font>
    </p>

    <h3 align="center">
      Pathology Report on [% c.cfg('settings').lab_name_abbreviation %] Ref No:
      [% PROCESS site/lab_number.tt; want_url=0 %]
    </h3>

    [% IF request.has_optional.clinical_trial;
        trial_number = get_trial_number(patient.id, data.request_trial.trial_id) %]
        <h4>
            <font color="green">
            CLINICAL TRIAL: [% data.request_trial.trial.trial_name %]
            [% IF trial_number %][ [% trial_number %] ][% END %]
            </font>
        </h4>
    [% END %]
  </center>

  <table width="100%" cellpadding="3">
    <tr>
      <td valign="top">
        <i><font size="+1">Patient ID</font></i>
        <blockquote>
          Name: <b>
            [% patient.last_name   | upper %],
            [% format_firstname(patient) || patient.first_name | ucfirst %]
            [% patient.middle_name | ucfirst %]
          </b> <br />
          DoB: [% patient.dob.strftime('%d.%b.%Y') %] <br />
		  [% IF patient.nhs_number %]
			NHS No: [% PROCESS site/nhs_number.tt nhs_number = patient.nhs_number %]
			[% IF data.patient_case.unit_number %]
			  [[% data.patient_case.unit_number %]]
		    [% END %]
		  [% ELSE;
                presentation = data.request_initial_screen.screen.description;
                trial_name   = data.request_trial.trial.trial_name;

			  UNLESS # one of exempted categories:
                  nhs_number_exempt.presentation.item(presentation) OR
                  nhs_number_exempt.clinical_trial.item(trial_name)
               %]
				NHS No: <font color="red"><b>please use the NHS no</b></font><br />
			  [% END %]
		    Hospital No: [% data.patient_case.unit_number || 'unknown' %]
		  [% END %]
        </blockquote>
      </td>
      <td valign="top"><i><font size="+1">Source</font></i>
        <blockquote>
          Referrer: [% data.referrer_department.referrer.name %]
		  [[% data.referrer_department.hospital_department.display_name %]] <br />
          Source: [% data.patient_case.referral_source.display_name | html %] <br />
          Date received: [% data.created_at.strftime('%d.%b.%Y %H:%m') %]
        </blockquote>
      </td>
    </tr>
  </table>

  <p>
    <font size="+1"><i>Specimen</i></font>
  </p>

  <blockquote>
    Type: [% request.specimen_map.item(data.id).description.join('; ') | html %]
    [% IF data.request_external_ref %]
        [[% data.request_external_ref.external_reference | html %]]
    [% END %]
    <br />
    [% IF data.request_report.gross_description %]
	  Gross description: [% data.request_report.gross_description | html %]<br />
	[% END %]
    Quality: [% data.request_report.specimen_quality %]
  </blockquote>

  [% UNLESS request.special_formatting.skip_clinical_details %]
  <p>
    <font size="+1"><i>Clinical Details</i></font>
  </p>

  <blockquote>
	[% symbolise(data.request_report.clinical_details) %]
  </blockquote>
  [% END %]

  [% # IF request.result_summaries.size; # not needed - will skip sections with results but no results_summary
	FOREACH section IN request.all_results; # PROCESS dumper.tt dump = section.key;
		# only want results_summary sections:
		NEXT UNLESS section.value.has_result_summary.match('yes');

		section_result_summary = request.result_summaries.item(section.key);
		test_results = [ ]; # reset array
        p53_data = {}; # for composite p21/p53 result

		FOREACH t IN section.value.test; # PROCESS dumper.tt dump = t;
		  NEXT UNLESS t.value.result;
		  IF t.value.result.match('\d'); # add % sign:
			t.value.result = t.value.result _ '%';
          END;

          # composite p21/p53 result:
          IF section.key == 'Immunohistochemistry';
            IF t.value.test_name == 'p21';
              p53_data.p21 = t.value.result; NEXT;
            ELSIF t.value.test_name == 'p53';
              p53_data.p53 = t.value.result; NEXT;
            END;
          END;

		  result = t.key _ '<sup>' _ t.value.result _ '</sup>';
		  test_results.push(result);
		END;

        IF p53_data.size; # PROCESS dumper.tt dump = p53_data;
            p53_result = 'p53' _ '<sup>' _ composite_p53(p53_data) _ '</sup>';
            test_results.push(p53_result);
        END;
	  %]

	  [% # skip unless results summary or test results:
		NEXT UNLESS section_result_summary || test_results.size %]
	  <p>
		[% section_name = section.key | lower %]
		<font size="+1">
		  <i>[% # ? override default section name eg imatinib monitoring:
			  request.special_formatting.section_name_map.item(section_name)
			  || section.key %] <!-- Summary -->
		  </i>
		</font>
	  </p>

	  [% IF test_results.size; result = test_results.join(' ') %]
		<blockquote><p>[% result %]</p></blockquote>
	  [% END %]

	  [% IF section_result_summary %]
	  <blockquote>
		<p>
		  [% UNLESS request.special_formatting.no_comment # eg imatinib monitoring %]
		  Comment:
		  [% END %]

		  [% # highlight section if timestamp > auth/report time:
			ref_time = request.status_options.authorised.is_active.match('yes')
			  ? history.authorised.time : history.reported.time;
			font_color = 'black'; # default
            # next line = fatal error if auth action not recorded in History file
			IF section_result_summary.time AND ref_time # so check they exist
			  AND section_result_summary.time > ref_time;
			  font_color = 'red'; is_amended_report = 1; # doesn't matter if it already is
			END;
		  %]
		  <font color="[% font_color %]">
			[% symbolise(section_result_summary.results_summary)
			  | html_line_break # escapeHTML already done %]
		  </font>
		</p>
	  </blockquote>
	  [% END %]

      <!-- BEGIN chart -->
      [% PROCESS site/make_chart.tt format_info = request.special_formatting %]
      <!-- END chart -->

	[% END %]
  [% # END %]

  [% UNLESS request.special_formatting.skip_morphology %]
  <p>
    <font size="+1"><i>Morphology &amp; Comments</i></font>
  </p>

  <blockquote>
	[%
	  raw_comment = line_break(data.request_report.comment);
	  formatted_comment = symbolise(raw_comment);
		# highlight 'additional comment' (manual input in comment field):
	  text = '<font color="red">ADDITIONAL COMMENT</font>';
	  formatted_comment.replace('[Aa]dditional [Cc]omment', text) | html_line_break;
	%]
  </blockquote>
  [% END %]

  [%
    UNLESS request.special_formatting.skip_diagnosis;

    diagnosis = data.request_report.diagnosis.name | html;

    IF request.previous_diagnoses.size;
        FOREACH entry IN request.previous_diagnoses; # PROCESS dumper.tt dump = entry.as_tree;
            IF entry.diagnosis.name != diagnosis # not same as diagnosis and not changed at auth:
                AND history.authorised.time.delta_days(entry.time).delta_days;
                diagnosis = '<font color="red">' _ diagnosis _ '</font>';
                LAST;
            END;
        END;
    END;
  %]
        <p>
            <font size="+1">
              <i>Diagnosis</i>: <b>[% diagnosis %]</b>
              [% IF data.request_report.diagnosis.icdo3 %]
                [[% data.request_report.diagnosis.icdo3 %]]
              [% END %]
            </font>
       </p>
  [% END %]

  [%
    context_warnings = [];
    IF context_warning_map.item(data.request_report.diagnosis.id);
        warning = context_warning_map.item(data.request_report.diagnosis.id);
        context_warnings.push(warning);
    END;
    IF request.specimen_map.item(data.id).description.join(' ').match('CSF')
        AND NOT data.request_report.diagnosis.icdo3.match('/3'); # non-ICDO3 + CSF
        warning = 'Absence of involvement of the cerebro-spinal fluid does not'
            _ ' exclude the possibility of intracerebral disease';
        context_warnings.push(warning);
    END;
    IF context_warnings.size;
  %]
    <p>
        <font color="green"><b>Note:
        [% context_warnings.join('; ') %]</b>
        </font>
    </p>
  [% END %]

  [% INCLUDE report/additional_comments.tt %]

  <p align="right">
    Reported by:
	<b>[% history.reported.user.first_name | ucfirst %]</b>
	<b>[% history.reported.user.last_name  | ucfirst %]</b>
	on [% history.reported.time.strftime('%d.%b.%Y at %H:%M') %]
  [% IF history.authorised %]
	<br />
    Report authorised by:
	<b>[% history.authorised.user.first_name | ucfirst %]</b>
	<b>[% history.authorised.user.last_name  | ucfirst %]</b>
	on [% history.authorised.time.strftime('%d.%b.%Y at %H:%M') %]
  [% END %]
  </p>

  [% BLOCK amended_report_update;
	  FOREACH entry IN request.previous_diagnoses;
          # PROCESS dumper.tt dump = entry.as_tree %]
        <p align="right">
          Amended report issued by:
            <b>[% entry.user.first_name | ucfirst %]</b>
            <b>[% entry.user.last_name  | ucfirst %]</b>
            on [% entry.time.strftime('%d.%b.%Y') %]
            at [% entry.time.strftime('%T').match('00:00:00') # for legacy data
                ? '??:??' : entry.time.strftime('%H:%M') %]
        </p>
    [% END %]
  [% END %]

  [%
    IF request.previous_diagnoses.size;
        FOREACH entry IN request.previous_diagnoses;
          IF history.authorised.time.delta_days(entry.time).delta_days; # ie not same date
            PROCESS amended_report_update;
            LAST; # only needed once
          END;
        END;
    END;
   %]

  [% IF dispatch_log.size %]
	<p align="right">
	[% FOREACH report IN dispatch_log %]
	  Report sent to:
		[% report.recipient %] on [% report.time.strftime('%d.%b.%Y at %H:%M') %]
		[% UNLESS loop.last %]<br />[% END %]
	[% END %]
	</p>
  [% END %]
  
[% END %]
<!-- END record/body.tt -->
