package votorola.s.wic; // Copyright 2011-2012, Michael Allan.  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Votorola Software"), to deal in the Votorola Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Votorola Software, and to permit persons to whom the Votorola Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Votorola Software. THE VOTOROLA SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE VOTOROLA SOFTWARE OR THE USE OR OTHER DEALINGS IN THE VOTOROLA SOFTWARE.

import com.sun.jersey.api.uri.*;
import java.io.*;
import javax.xml.stream.*;
import org.apache.wicket.*;
import org.apache.wicket.markup.html.basic.*;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.link.*;
import org.apache.wicket.markup.html.panel.*;
import org.apache.wicket.model.*;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import votorola.a.*;
import votorola.a.count.*;
import votorola.a.position.*;
import votorola.a.voter.*;
import votorola.a.web.wic.*;
import votorola.a.web.wic.authen.*;
import votorola.g.lang.*;
import votorola.g.web.wic.*;
import votorola.s.wic.count.*;


/** A page that redirects to the user's draft, or, if there is no draft, guides the user
  * in creating one.  It supports <a href='WP_Draft.html#devMode'>GWT dev mode</a> and the
  * <a href='WP_Draft.html#xf'>relaying of state</a> between Crossforum Theatre pages.  An
  * example request is:
  *
  * <blockquote><code><a href="http://reluk.ca:8080/v/w/MyDraft?p=Sys!p!sandbox" target='_top'>http://reluk.ca:8080/v/w/MyDraft?p=Sys!p!sandbox</a></code></blockquote>
  *
  * <h3>Query parameters</h3>
  *
  * <table class='definition' style='margin-left:1em'>
  *     <tr>
  *         <th class='key'>Key</th>
  *         <th>Value</th>
  *         <th>Default</th>
  *         </tr>
  *     <tr><td class='key'>p</td>
  *
  *         <td>The {@linkplain votorola.a.count.Poll#name() poll name}.  Any slash
  *         characters (/) may be encoded as exclamation marks (!).</td>
  *
  *         <td>Null, resulting in a 303 (see other) redirect that fills in the name of
  *         the {@linkplain votorola.a.count.Poll#TEST_POLL_NAME test poll}.</td>
  *
  *         </tr>
  *     <tr><td class='key'>ru</td>
  *
  *         <td>The username of the user in the remote wiki 'rw', if known.</td>
  *
  *         <td>None</td>
  *
  *         </tr>
  *     <tr><td class='key'>rw</td>
  *
  *         <td>A remote wiki in which to create the draft if it does not exist.  Specify
  *         the wiki by the URL for its index script, without a trailing slash (/).  For
  *         example "rw=http://reluk.ca/mediawiki/index.php".  Do not specify the local
  *         pollwiki here, or a local draft will be created in remote form.</td>
  *
  *         <td>None</td>
  *
  *         </tr>
  *     </table>
  *
  *     @see <a href='../../../../../a/position/WP_MyDraft.html' target='_top'>WP_MyDraft.html</a>
  *     @see <a href='http://mail.zelea.com/list/votorola/2011-December/001259.html'>Guided creation of new drafts in the pollwiki</a>
  */
  @ThreadRestricted("wicket") @org.apache.wicket.devutils.stateless.StatelessComponent
public final class WP_MyDraft extends VPageHTML
{

    // Do not localize this page till draft creation is properly automated, as the content
    // is too verbose.


    /** Constructs a WP_MyDraft.
      */
    public WP_MyDraft( final PageParameters pP ) throws IOException, XMLStreamException // bookmarkable page iff constructor public & (default|PageParameter)
    {
        super( pP );

        final VRequestCycle cycle = VRequestCycle.get();
        final VOWicket app = VOWicket.get();
        final VSession.User user = VSession.get().user();
        if( user == null )
        {
            pP.set( "returnClass", getClass().getName() );
            throw new RestartResponseException( app.authenticator().newLoginPage( pP ));
        }

        final String pollName = Poll.U.toName( WP_Poll.maybeRedirect_P( WP_MyDraft.class, pP,
          cycle ));

      // Either redirect to the user's existing draft ...
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        final String coreLoc = WP_Draft.maybeRedirectToDraft( user.username(), pollName,
          /*contextPersonName*/null, app, cycle );

      // ... or explain how to create a new draft.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        add( new WC_NavigationHead( "navHead", WP_MyDraft.this, cycle ));
        final Model<String> titleModel = new Model<String>( "Create a draft" );
        add( new Label( "title", titleModel ));
        add( new Label( "h", titleModel ));

        final VoteServer vS = app.vsRun().voteServer();
        final String remoteWikiIndexScript = stringNonEmpty( pP, "rw" );
          // We could try to guard here against 'rw' specifying the local wiki, but there
          // is no easy way to know the canonical URL of the local wiki.  We cannot assume
          // that vS.pollwiki().scriptURI() is set to anything but an alias.  So instead of
          // guarding against an erroneous local 'rw' here in the code, we document a rule
          // against it in the API and let it fail consistently (as documented) if that
          // rule is broken.
        if( remoteWikiIndexScript == null ) initLocal( vS, user, coreLoc, pP );
        else initRemote( vS,pollName, user, coreLoc, remoteWikiIndexScript, pP );
    }



    private final @Warning("init call") void initLocal( final VoteServer vS, final IDPair user,
      final String coreLoc, final PageParameters pP )
    {
        final Fragment y = new Fragment( "instruct", "localFrag", WP_MyDraft.this );
        add( y );

      // Local login.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        addLocalLogin( y, user, vS );

      // Local paste.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        y.add( newLocalPasteLink( coreLoc ));
    }



    private final @Warning("init call") void initRemote( final VoteServer vS,
      final String pollName, final IDPair user, final String coreLoc,
      final String remoteWikiIndexScript, final PageParameters pP )
    {
        final Fragment y = new Fragment( "instruct", "remoteFrag", WP_MyDraft.this );
        add( y );

      // Remote username.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        final IModel<String> remoteUsername;
        {
            final String ru = stringNonEmpty( pP, "ru" );
            final Model<String> ruInput = new Model<String>( ru );
            if( ru == null )
            {
                final Fragment fragment = new Fragment( "ru", "ruFrag", WP_MyDraft.this );
                y.add( fragment );
                fragment.add( new ExternalLink( "remoteWikiLink", remoteWikiIndexScript
                  + "?title=Special:MyPage", "drafting wiki" ));

                final Form<Void> form = new Form<Void>( "form" );
                fragment.add( form );
                form.add( new TextField<String>( "ruInput", ruInput ));
                form.add( new Button( "reload" ));
            }
            else y.add( newNullComponent( "ru" ));

            ruInput.setObject( ru );
            remoteUsername = new AbstractReadOnlyModel<String>()
            {
                public @Override String getObject()
                {
                    final String o = ruInput.getObject();
                    return o == null? "USERNAME": o; // in case user enters nothing
                }
            };
        }

      // Remote login.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        {
            final Label label = new Label( "remoteUsername", remoteUsername );
            y.add( label );
            label.setRenderBodyOnly( true );

            final Model<String> href = new Model<String>( remoteWikiIndexScript
              + "?title=Special:UserLogin" );
            y.add( new ExternalLink( "remoteLoginLink", href, href ));
        }

      // Local login.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        addLocalLogin( y, user, vS );

      // Local copy.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        final IModel<String> remoteDraftName = new AbstractReadOnlyModel<String>()
        {
            public @Override String getObject()
            {
                return "User:" + remoteUsername.getObject() + "/" + pollName;
            }
        };
        {
            final Label label = new Label( "draftPointer-index", remoteWikiIndexScript );
            y.add( label );
            label.setRenderBodyOnly( true );
        }
        {
            final Label label = new Label( "draftPointer-page", remoteDraftName );
            y.add( label );
            label.setRenderBodyOnly( true );
        }

      // Local paste.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        y.add( newLocalPasteLink( coreLoc ));

      // Remote copy.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        {
            final Label label = new Label( "localUsername", user.username() );
            y.add( label );
            label.setRenderBodyOnly( true );
        }
        {
            final Label label = new Label( "draftPoll", pollName );
            y.add( label );
            label.setRenderBodyOnly( true );
        }

      // Remote paste.
      // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        {
            final IModel<String> href = new AbstractReadOnlyModel<String>()
            {
                public @Override String getObject()
                {
                    return remoteWikiIndexScript + "?action=edit&title=" + UriComponent.encode(
                      remoteDraftName.getObject().toString(), UriComponent.Type.QUERY_PARAM );
                }
            };
            y.add( new ExternalLink( "remotePasteLink", href, href ));
        }
    }



//// P r i v a t e ///////////////////////////////////////////////////////////////////////


    private static void addLocalLogin( final MarkupContainer y, final IDPair user,
      final VoteServer vS )
    {
        final Label label = new Label( "userEmail", user.email() );
        y.add( label );
        label.setRenderBodyOnly( true );

        final Model<String> href = new Model<String>( vS.pollwiki().appendPageSpecifier(
          "Special:UserLogin" ).toString() );
        y.add( new ExternalLink( "localLoginLink", href, href ));
    }



    private static ExternalLink newLocalPasteLink( final String coreLoc )
    {
        final Model<String> href = new Model<String>( coreLoc
          + (coreLoc.lastIndexOf("?") < 0? "?": "&") + "action=edit" );
        return new ExternalLink( "localPasteLink", href, href );
    }



}