#include "sample2.h"
#include "dialog.h"

#include XColor_i
#include XMessageBox_i
#include XException_i
#include XDragHandler_i
#include XSlider_i
#include XString_i
#include XBubbleHelp_i
#include XWebView_i

#include <stdlib.h>

MyApp * app;

class MyAboutWin: public XFrameWindow
{
  public:
    MyAboutWin( XResource *);
    BOOL DoCommand( LONG);
};


BOOL MyAboutWin :: DoCommand( LONG com)
{
   if( com == DID_PUSH_OK)  //ok-button pressed, close window
      delete this;//Close();
   return TRUE;
}


MyAboutWin :: MyAboutWin ( XResource * r): XFrameWindow ( r, "About", XFrameWindow::defaultDialogStyle | FRM_CENTER, NULL, NULL, TRUE)
{
}


BOOL MyApp :: QueryForQuit( void )
{
  XMessageBox mBox( "Do you realy want to quit?", "To the User", MB_YESNO | MB_ICONQUESTION|MB_MOVEABLE, window);

  if( mBox.GetCommand() == MBID_YES)
     return TRUE;
  else
     return FALSE;
}


BOOL MyAppWindow :: QueryForClose( void )
{
  XMessageBox mBox( "Ready to go?", "To the User", MB_YESNO | MB_ICONQUESTION|MB_MOVEABLE, this);

  if( mBox.GetCommand() == MBID_YES)
     {
        app->Terminate();//close all windows
        return TRUE;
     }
  else
     return FALSE;
}


class MyBubble: public XBubbleHelp
{
   public:
      MyBubble( XResource * r, XWindow*w): XBubbleHelp(r, w) { ;}
      BOOL SetMsgText( ULONG windowID );
};


BOOL MyBubble :: SetMsgText( ULONG windowID )
{
   switch( windowID)
      {
         case IDM_BACK:
            SetText( "Move backward");
            break;
         case IDM_HOME:
            SetText("Move to the homepage");
            break;
         case IDM_FORWARD:
            SetText("Move Foreward");
            break;
         case IDM_ANIMATION:
            SetText("Start/Stop loading the document");
            break;
         case 100:
            SetText( "Enter an adress or select a loaded document");
            break;
         default:
            return FALSE;
      }
   return TRUE;
}


class MyWebView: public XWebView
{
      MyAppWindow * win;
      BOOL loadError;
   public:
      MyWebView(XWindow * w):XWebView(w, NULL,500) { win = (MyAppWindow*) w; }
      void ButtonPressed( SHORT num, SHORT x, SHORT y) { SetFocus(); }
      virtual void HandleError( ULONG, char* );
      LONG Load( const char * url, const BOOL reload = FALSE);
      void LoadResult( LONG res);
      void LoadProgress( LONG status );
};


void MyWebView :: LoadProgress( LONG status)
{
   switch(status)
      {
         case WEB_CONNECT:
            win->text2->SetText( "connecting.." );
            break;
         case WEB_WAIT:
            win->text2->SetText( "waiting for reply.." );
            break;
         case WEB_LOADDATA:
            win->text2->SetText( "loading data.." );
            break;
         case WEB_RENDER:
            win->text2->SetText( "building document.." );
            break;
      }
}


void MyWebView :: HandleError( ULONG errorCode, char * errorMsg)
{
   loadError = TRUE;
   XString msg = "Error: ";
   if(errorMsg)
      msg += errorMsg;
   win->text2->SetText( (char*) msg);
   XProcess::Beep( 400, 300);
}


void MyWebView :: LoadResult( LONG res)
{
   win->animation->Animate(FALSE);
 
   if( res == WEB_SUCCESS && loadError == FALSE)
      {
         XString buffer1, buffer2;
         win->GetText( &buffer1 );
         ULONG f;
         if( buffer1.Find(f, ":"))
            buffer1 = buffer1.Left(f);
         GetDocTitle( &buffer2 );
         buffer1 = buffer1 + ": " + buffer2;
         win->SetText( buffer1 );

         win->text2->SetText( "Document done");
      }
   if( res == WEB_ERROR)
      {
         XProcess::Beep(400, 500);
         win->text2->SetText( "Error ocured!");
      }
   if( res == WEB_CANCELLED)     
      win->text2->SetText( "Load interrupted");
}


LONG MyWebView :: Load( const char * url, const BOOL reload)
{                  
   loadError = FALSE;
   if( strstr(url, "#") == NULL)
      {
         win->animation->Animate(TRUE, FALSE);
         XString msg = "Loading: ";
         msg += url;
         win->text2->SetText( msg);
      }
   if( win->http->SearchString( url ) == LS_NONE)
     {
         win->loading = TRUE;
         win->http->InsertItem( url, 0);
         win->http->SelectItem( 0);
         win->loading = FALSE;
     }

   XWebView::Load(url, reload);

   return 0;
}


class MyToolBar: public XToolBar
{
   public:
      MyToolBar( XFrameWindow*w, SHORT id):XToolBar(w, TB_TOP|TB_RIPABLE, id) { ;}
      void Cut( void );
};


void MyToolBar :: Cut( void )
{
   XToolBar::Cut();
   if( GetWindowID() == 800)
      GetCutWindow()->SetText( "ToolBar 1" );
   else
      GetCutWindow()->SetText( "ToolBar 2" );
}


MyAppWindow :: MyAppWindow( XApplication * app, XResource r ): XFrameWindow( &r, "Sample2 - Itīs not Netscape", XFrameWindow::defaultStyle | FRM_MINBUTTON | FRM_TASKLIST | FRM_ICON )
{
   XColor col( COL_WHITE);
   SetBackgroundColor( &col );

   //create a helpinstance
   help = new XHelpInstance( "sample2.hlp", app, "Sample2 - Help");
   //associate the help with this function
   help->AssociateWindow( this );

   //we want a menubar, it is defined in the resources of the exe-file with the id IDM_MAIN
   XResource rs( IDM_MAIN, app->GetResourceLibrary());
   menu = new XMenuBar( this, &rs);

   //we create a toolbar for the buttons at the top...
   toolBar1 = new MyToolBar( this, 800);

   //now create pushbuttons with bitmaps, the bitmaps must be in the resources of the exe
   XRect rec( 0, 0, 30, 30);
   back = new XPushButton( toolBar1, &rec, (USHORT) IDM_BACK, BU_BITMAP);
   forward = new XPushButton( toolBar1, &rec, (USHORT) IDM_FORWARD, BU_BITMAP);
   home = new XPushButton( toolBar1, &rec, (USHORT) IDM_HOME, BU_BITMAP);

   //add the pushbuttons to the toolbar, the toolbar will use the size of the first button
   toolBar1->AddWindow( back , FALSE, TRUE);
   toolBar1->AddWindow( forward );
   toolBar1->AddWindow( home );

   /*create another toolbar*/
   toolBar2 = new MyToolBar( this, 900);
   toolBar2->SetHeight( 50 );

   XRect r1( 0, 0, 80, 20);
   text = new XStaticText( toolBar2, "Location:", &r1, TX_RIGHT);
   XColor black( COL_BLACK);
   text->SetForegroundColor( &black);

   toolBar2->AddWindow( text, FALSE, FALSE, NULL, 0, -23);

   /*create a combo-box, it get the id 100, so its associated with the helpinstance*/
   XRect r2( 0, 0, 490, 200);
   http = new XComboBox(toolBar2, &r2, 100);

   toolBar2->AddWindow( http, TRUE, FALSE, NULL, -10, - 20);

   /* now a graphic-button will be created. the button displays a simple animation. */
   /* to do so, the buttons needs a list of bitmap-IDs (from bitmaps in the resources)*/
   /* which build the animation. in this case we have 6 bitmaps */
   SHORT list[6] = {STAR1, STAR2, STAR3, STAR4, STAR5, STAR6};

   /* give in the constructor the styles for playing animation. additionaly the button */
   /* has two states (if you press the button, it will not come up automaticaly */
   /* the id IDM_ANIMATION is also in the help-file so help will be displayed automaticaly */
   XRect r0(0,0,0,0);
   animation = new XGraphicButton( toolBar2, &r0, IDM_ANIMATION, WIN_VISIBLE | GB_ANIMATION, "", 6, list);

   /* set the speed of the animation */
   animation->SetAnimationRate( 50 );

   /* add the button to the toolbar */
   toolBar2->AddWindow( animation, FALSE, TRUE, NULL, 10);

   /*..and a toolbar at the bottom*/
   toolBar3 = new XToolBar( this, TB_BOTTOM);
   toolBar3->SetHeight( 30);

   XRect r3(0,0,40,40);
   key = new XStaticBitmap( toolBar3, &r3, IDM_KEY);
   toolBar3->AddWindow( key, FALSE, FALSE, NULL, 10, -3);

   XRect r4( 0,0, 520, 20);
   border = new XStaticFrame( toolBar3, &r4);
   toolBar3->AddWindow( border, TRUE, FALSE, 0, -4);

   XRect r5( 0, 0, 500, 15);
   text2 = new XStaticText( toolBar3, "", &r5, TX_LEFT | TX_VCENTER);
   text2->SetForegroundColor( &black );
   text2->SetFont( "8.Helv");

   toolBar3->AddWindow( text2, FALSE, FALSE, NULL, -505, -3);

   //setup the menu
   menu->CheckItem( IDM_TOOLBAR );
   menu->CheckItem( IDM_URL );
   menu->CheckItem( IDM_STATUSLINE );

   XRect rect( 100, 100, 670, 500);
   SetSize( &rect);

   Activate();

   XResource resource2(0, r.GetResourceLibrary());
   MyBubble * b1 = new MyBubble( &resource2, toolBar1);
   MyBubble * b2 = new MyBubble( &resource2, toolBar2);

   loading = FALSE;

   webView = new MyWebView( this );
   SetClient( webView );
   http->InsertItem( "sample2.htm", 0);
   http->SelectItem(0);

   webView->SetFocus();
}


void MyAppWindow :: DoControl( XControlEvent * e)
{
   if( (e->GetEventID() == WIN_ENTER || e->GetEventID() == WIN_SELECTED) && e->GetWindowID() == 100 && loading == FALSE)
      {
         if( (http->GetSelection() == LS_NONE && e->GetEventID() == WIN_SELECTED) || loading == TRUE)
            return;
         XString url;
         SHORT res;
         if( e->GetEventID() == WIN_ENTER )
            http->GetText( &url );
         else
            {
               res=http->GetSelection();
               http->GetItemText(res, &url);
               http->SetText(url);
            }

         if(url.GetLength() == 0)
            return;

         res = http->SearchString( url );
         if( res == LS_NONE )
            http->InsertItem( url, 0);
         webView->Load( url );
      }
}


BOOL MyAppWindow :: DoCommand( LONG com)
{
  switch(com)
     {
        case IDM_BACK:
           {
              SHORT res = http->GetSelection();
              http->SelectItem( 1 + res );
           }
           break;
        case IDM_ANIMATION:
           if( animation->IsSelected() == TRUE)
              webView->StopLoading();
           break;
        case IDM_ABOUT:  //menuitem <about> selected, show the window
           {
              XResource res( DIALOG_ABOUT, app->GetResourceLibrary());
              MyAboutWin * win = new MyAboutWin( &res);
              win->ShowModal( this );
           }
           break;
        case IDM_TOOLBAR:
           {
              if( toolBar1->IsVisible())
                 {
                    menu->CheckItem( IDM_TOOLBAR, FALSE);
                    toolBar1->Show(FALSE);
                 }
              else
                 {
                    menu->CheckItem( IDM_TOOLBAR, TRUE);
                    toolBar1->Show();
                 }
           }
           break;
        case IDM_STATUSLINE:
           {
              if( toolBar3->IsVisible())
                 {
                    menu->CheckItem( IDM_STATUSLINE, FALSE);
                    toolBar3->Show(FALSE);
                 }
              else
                 {
                    menu->CheckItem( IDM_STATUSLINE, TRUE);
                    toolBar3->Show();
                 }
           }
           break;
        case IDM_URL:
           {
              if( toolBar2->IsVisible())
                 {
                    menu->CheckItem( IDM_URL, FALSE);
                    toolBar2->Show(FALSE);
                 }
              else
                 {
                    menu->CheckItem( IDM_URL, TRUE);
                    toolBar2->Show();
                 }
           }
           break;
        case IDM_HELP_HELP:
           help->ShowHelpForHelp();
           break;
        case IDM_HELP_INDEX:
           help->ShowHelpIndex();
           break;
     }
   return TRUE;
}


void main ( void)
{
   try
   {
      app = new MyApp();  //create a new application

      XResource r( IDM_ICON, app->GetResourceLibrary());

      app->window = new MyAppWindow( app, r );   //create new framewindow (see above)
      app->Start();               //let the application work
   }
   catch( XException e)
   {
      XMessageBox( e.GetErrorMessage());
      exit(-1);
   }
}
