<%args>
    $session_id => undef
    $pkcs10     => undef
    $testresult => undef
</%args>
<%method title>
  OpenXPKI - <% i18nGettext('I18N_OPENXPKI_WF_TYPE_SMARTCARD_PERSONALIZATION') %>
</%method>
<%method onload>\
% if (exists $ARGS{testresult}) {
onload="InstallCertIEAndTest(document.OpenXPKI)"
% }
</%method>
<%init>
#    use MIME::Base64;

    my @errors;
    my $debug_msg;

    my $wf_type = 'I18N_OPENXPKI_WF_TYPE_SMARTCARD_PERSONALIZATION';
    
    # search for workflows of type I18N_OPENXPKI_WF_TYPE_SMARTCARD_...
    # with creator = current user
    my $user = $context->{client}->send_receive_command_msg('get_user')->{PARAMS};
    $m->comp ('/lib/debug.mhtml',
              'level' => 1,
              'msg'   => 'user: ' . $user,
    );
    my $msg;
    if (defined $user) {
        $msg = $context->{client}->send_receive_command_msg(
            'search_workflow_instances',
            {
                TYPE    => $wf_type,
                CONTEXT => [ {
                    KEY   => 'creator',
                    VALUE => $user
                } ],
            },
        );
    }    
    $m->comp('/lib/debug.mhtml',
        'level' => 10,
        'msg'   => 'msg: ' . Dumper($msg),
    );
    my @workflow_ids;
    if (defined $msg && $msg->{SERVICE_MSG} eq 'ERROR') {
        @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $msg) ] ;
    }
    else {
        eval {
            @workflow_ids = @{$msg->{PARAMS}};
        };
        $m->comp ('/lib/debug.mhtml',
            'level' => 1,
            'msg'   => 'workflow_ids: ' . Dumper(\@workflow_ids),
        );
    }
    # decide by number of entries what to to
    # 0 - create new workflow
    # 1 - re-entry at given state
    # > 1 present dialog? (date, state)
    # TODO -- filter those that are in state FAILURE (or SUCCESS?)
    
    my $wf_info;
    if (scalar @workflow_ids == 0) { # no workflow available
        my $c_msg = $context->{client}->send_receive_command_msg(
            'create_workflow_instance',
            {
                WORKFLOW => $wf_type,
            },
        );
        if ($c_msg->{SERVICE_MSG} eq 'ERROR') {
            @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $c_msg) ] ;
        }
        $wf_info = $c_msg->{PARAMS}->{WORKFLOW};
        $debug_msg = $c_msg;
    }
    elsif (scalar @workflow_ids == 1) { # re-entry into workflow
        my $i_msg = $context->{client}->send_receive_command_msg(
            'get_workflow_info',
            {
                WORKFLOW => $wf_type,
                ID       => $workflow_ids[0]->{'WORKFLOW.WORKFLOW_SERIAL'},
            },
        );
        if ($i_msg->{SERVICE_MSG} eq 'ERROR') {
            @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $i_msg) ] ;
        }
        $wf_info = $i_msg->{PARAMS}->{WORKFLOW};
        $debug_msg = $i_msg;
    }
    my $wf_id = $wf_info->{ID};

    if ($wf_info->{STATE} eq 'ISSUANCE_PENDING' ||
        $wf_info->{STATE} eq 'WAITED_FOR_CHILDREN') { # check whether we can advance to the next state
        # TODO
        # the || is a workaround for bug #1602288 (so we are at least not
        # stuck in WAITED_FOR_CHILDREN if it happens)
        my $g_msg = $context->{client}->send_receive_command_msg(
            'get_workflow_activities',
            {
              WORKFLOW => $wf_type,
              ID       => $wf_id,
            },   
        );
        my @list;
        if ($g_msg->{SERVICE_MSG} eq 'ERROR') {
            @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $g_msg) ];
        }
        else {
            @list = @{$g_msg->{PARAMS}};
            if (scalar @list == 1) { # execute activity
                my $e_msg = $context->{client}->send_receive_command_msg(
                    'execute_workflow_activity',
                    {
                    WORKFLOW => $wf_type,
                    ID       => $wf_id,
                    ACTIVITY => $list[0],
                    },   
                );
            }
        }
        my $i_msg = $context->{client}->send_receive_command_msg(
            'get_workflow_info',
            {
                WORKFLOW => $wf_type,
                ID       => $workflow_ids[0]->{'WORKFLOW.WORKFLOW_SERIAL'},
            },
        );
        if ($i_msg->{SERVICE_MSG} eq 'ERROR') {
            @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $i_msg) ] ;
        }
        $wf_info = $i_msg->{PARAMS}->{WORKFLOW};

    }
    if ($wf_info->{STATE} eq 'FAILURE') { # failed because of LDAP
         @errors = [ 'I18N_OPENXPKI_HTML_SMARTCARD_FAILURE_ISSUANCE_IMPOSSIBLE' ]; # TODO: does this work?
    }
    $m->comp ('/lib/debug.mhtml',
        'level' => 1,
        'msg'   => 'wf_info: ' . Dumper($wf_info),
    );

    # if PKCS#10 data is available, call create_server_csr
    if ($pkcs10 ne '' && $pkcs10 !~ m{^-----BEGIN}xs) {
        $pkcs10 = "-----BEGIN CERTIFICATE REQUEST-----\n".
                  $pkcs10.
                  "-----END CERTIFICATE REQUEST-----";
    }
    if ($pkcs10 ne '' && $wf_info->{STATE} eq 'CERTIFICATE_ISSUANCE_POSSIBLE') {
        my $e_msg = $context->{client}->send_receive_command_msg(
            'execute_workflow_activity',
            {
              WORKFLOW => $wf_type,
              ID       => $wf_id,
              ACTIVITY => 'create_server_csr',
              PARAMS   => {
                'pkcs10' => $pkcs10,
              },
            },   
        );
        # get updated workflow info
        if ($e_msg->{SERVICE_MSG} eq 'ERROR') {
            @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $e_msg) ];
        }
        my $i_msg = $context->{client}->send_receive_command_msg(
            'get_workflow_info',
            {
                WORKFLOW => $wf_type,
                ID       => $workflow_ids[0]->{'WORKFLOW.WORKFLOW_SERIAL'},
            },
        );
        if ($i_msg->{SERVICE_MSG} eq 'ERROR') {
            @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $i_msg) ] ;
        }
        $wf_info = $i_msg->{PARAMS}->{WORKFLOW};
    }

    # if testresult is non-empty, call write_certificate_test_result
    if ($testresult ne '' && $wf_info->{STATE} eq 'INSTALL_CERTIFICATE') {
        my $e_msg = $context->{client}->send_receive_command_msg(
            'execute_workflow_activity',
            {
              WORKFLOW => $wf_type,
              ID       => $wf_id,
              ACTIVITY => 'write_certificate_test_result',
              PARAMS   => {
                'testresult' => $testresult,
              },
            },   
        );
        # get updated workflow info
        if ($e_msg->{SERVICE_MSG} eq 'ERROR') {
            @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $e_msg) ];
        }
        my $i_msg = $context->{client}->send_receive_command_msg(
            'get_workflow_info',
            {
                WORKFLOW => $wf_type,
                ID       => $workflow_ids[0]->{'WORKFLOW.WORKFLOW_SERIAL'},
            },
        );
        if ($i_msg->{SERVICE_MSG} eq 'ERROR') {
            @errors = [ $m->comp('/lib/get_deep_error.mhtml', 'msg' => $i_msg) ] ;
        }
        $wf_info = $i_msg->{PARAMS}->{WORKFLOW};
    }

    my $total_certs = $wf_info->{CONTEXT}->{nr_of_certs};
    my $steps = 2*$total_certs + 1;
</%init>
<%once>
</%once>

% if (defined $wf_info) {
%   if ($wf_info->{STATE} eq 'CERTIFICATE_ISSUANCE_POSSIBLE') {
      <& './get_certificate_request.mhtml',
            'wf_info' => $wf_info,
            'steps'   => $steps, &>
%   }
%   elsif ($wf_info->{STATE} eq 'PENDING'
%       || $wf_info->{STATE} eq 'APPROVAL') {
      <& './waiting_for_approval.mhtml' &>
%   }
%   elsif ($wf_info->{STATE} eq 'ISSUANCE_PENDING') {
      <& './waiting_for_issuance.mhtml' &>
%   }
%   elsif ($wf_info->{STATE} eq 'INSTALL_CERTIFICATE') {
      <& './install_certificate.mhtml',
             'wf_info'    => $wf_info,
             'testresult' => $testresult,
             'steps'      => $steps &>
%   }
%   elsif ($wf_info->{STATE} eq 'SUCCESS') {
      <& './success.mhtml', 
            'steps'   => $steps  &>
%   }
%   elsif ($wf_info->{STATE} eq 'FAILURE') {
      <& './failure.mhtml',
            'wf_info' => $wf_info,
            'steps'   => $steps, &>
%   }
%   else {
<H1>I18N_OPENXPKI_HTML_SMARTCARD_ERROR_UNKNOWN_STATE_TITLE</H1>
<p>I18N_OPENXPKI_HTML_SMARTCARD_ERROR_UNKNOWN_STATE_DESC</p>
<pre>
state = <% $wf_info->{STATE} %>
debug_msg = <% Dumper($debug_msg) %>
wf_info = <% Dumper($wf_info) %>
errors = <% Dumper(\@errors) %>
</pre>
%   }
% }
% else { # we do not have $wf_info !
<H1>I18N_OPENXPKI_HTML_SMARTCARD_ERROR_NO_WF_INFO_TITLE</H1>
<p>I18N_OPENXPKI_HTML_SMARTCARD_ERORR_NO_WF_INFO_DESC</p>
<pre>
debug_msg = <% Dumper($debug_msg) %>
errors = <% Dumper(\@errors) %>
</pre>
% }
<!-- TODO: use own print_errors or make a generic print_errors -->
<& ./print_errors.mhtml, 'errors' => \@errors &>

