/*****************************************************************************
 * 
 * Nom                          : utils.c
 * desc                         : utilitaires projet
 *
 * version                      : $VER: utils.c 2.2ß4 (17.10.98)
 *
 * ver 2.1:   error handling
 * ver 2.2:   some bug fixed
 * ver 2.2ß2: stay in the background now
 * ver 2.2ß3: LoadConf used a uninitialized variable (pointer to WBScreen)
 * ver 2.3ß4: problem when notifyint was not present
 *            draw or not the seconds arrow
 *             
 *****************************************************************************
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <exec/exec.h>
#include <exec/ports.h>
#include <exec/io.h>
#include <exec/tasks.h>
#include <exec/libraries.h>
#include <dos/datetime.h>
#include <dos/dosextens.h>
#include <workbench/workbench.h>
#include <libraries/notifyintuition.h>

#include <proto/exec.h>
#include <proto/intuition.h>
#include <proto/dos.h>
#include <proto/graphics.h>
#include <proto/gadtools.h>
#include <proto/icon.h>
#include "utils.h"
#include "timer.h"
#include "tracewin.h"
#include "notify.h"
#include "partial.h"
#include "conf.h"
#include "obp.h"

struct Library * NotifyIntuitionBase ;


char * ptrTime = NULL ;
struct DateTime * dt = NULL ;

idWin * init(WBArg * appName) {
  /* initalize the main window
   * and the project
   */
  struct Screen  * WBScreen = NULL ;                 // lock on WB
  idWin * prjWin = NULL ;                            // main prj
  
  
  if ((prjWin = AllocVec(sizeof(idWin), MEMF_PUBLIC|MEMF_CLEAR)) == NULL)
    return(NULL) ;
    
    
  if ((prjWin->date = AllocVec(sizeof(struct DateStamp), MEMF_PUBLIC)) == NULL) {
    close(prjWin) ;
    return(NULL) ;
  }
    
  if ((prjWin->Notify = AllocVec(sizeof(struct IntNotifyRequest), MEMF_PUBLIC|MEMF_CLEAR)) == NULL) {
    close(prjWin) ;
    return(NULL) ;
  }
  
  
  if ((NotifyIntuitionBase = OpenLibrary(NOTIFYINTUITIONNAME, NOTIFYINTUITION_VMIN)) != NULL) {
        /* open the window
         */
    
    WBScreen = LockPubScreen("Workbench") ;
    top = WBScreen->BarHeight ; 
    prjWin->wb   = WBScreen ;
    LoadConf(prjWin) ;
    init_bitmap(prjWin) ;
    prjWin->win = OpenWindowTags(NULL, WA_Left,   prjWin->backWin.posX,
                                       WA_Top,         prjWin->backWin.posY,
                                       WA_Width,       prjWin->backWin.width,
                                       WA_Height,      prjWin->backWin.height,
                                       WA_IDCMP,       IDCMP,
                                       WA_MinWidth,      50,
                                       WA_MinHeight,   50,
                                       WA_MaxHeight,   MAXH,
                                       WA_MaxWidth,    MAXH,
                                       WA_Flags,       WFLG,
                                       WA_ScreenTitle, TXT_SCRTITLE,
                                       WA_NewLookMenus, TRUE,
                                       WA_PubScreenName, "Workbench", TAG_DONE) ;
    
    szgdg.Height = top - 1 ;
    szgdg.NextGadget = &tagdg ;
    tagdg.LeftEdge  = prjWin->win->Width /2 ;
    tagdg.TopEdge   = prjWin->win->Height - 20 ;
    tagdg.Width     = prjWin->win->Width /2 ;
    tagdg.Height    = 20 ;
  
    AddGList(prjWin->win, &szgdg, 0, 2, NULL) ;
   
    RefreshGList(&szgdg, prjWin->win, NULL, -1) ;
                                                                                             
    if (prjWin->win == NULL)
      return(NULL) ;
   
    if (prjWin->wb)
      UnlockPubScreen(NULL, WBScreen) ;
    
                                                                                                
          // initialisation ...  (fenetre...)
  }else {
    ez_req("Backclock Error", "Couldn't open notifyintuition.library V2", "Quit", NULL ) ;
    if (prjWin->Notify) FreeVec(prjWin->Notify) ;
    prjWin->Notify = NULL ;
    close(prjWin) ;
    return(NULL) ;
  }
  
  if (!initTimer(prjWin))   { close(prjWin) ; return(NULL) ;}
  if (!startNotify(prjWin)) { close(prjWin) ; return(NULL) ;}
  if ((ptrTime = AllocVec(LEN_DATSTRING, MEMF_PUBLIC|MEMF_CLEAR)) == NULL) {close(prjWin) ; return(NULL) ;}
  if ((dt =      AllocVec(sizeof(struct DateTime),  MEMF_PUBLIC|MEMF_CLEAR)) == NULL) {close(prjWin) ; return(NULL) ;}
  getDate(prjWin) ;
  initwin(prjWin) ;
  return prjWin ;
}

void close(idWin * prj) {
  int i;
  if (prj) {                              // struct prj existe (<>0) 
    endNotify(prj) ;
    if (prj->win) CloseWindow(prj->win) ; // ferme la fenetre
    free_twin(prj) ; 
    if (prj->date) FreeVec(prj->date) ;   // libere datestamp 
    if (prj->Notify) FreeVec(prj->Notify) ; // libere struct IntNotify
    closeTimer(prj) ;
    
    if (NotifyIntuitionBase) CloseLibrary(NotifyIntuitionBase) ;
    prj->wb = LockPubScreen("Workbench") ;
    for(i = 0; i<NUM_COLORS; i++)
      freePen(prj, prj->backWin.cmap[i].reg) ;
    if (prj->wb) UnlockPubScreen(NULL, prj->wb) ;
    if (ptrTime) FreeVec(ptrTime) ;
    free_bitmap(prj) ;
    FreeVec(prj) ;                        // libere la memoire
    FreeVec(dt) ;
  }
}
void getDate(idWin * prj) {
  // remplit la structure (projet) avec la date
   
  DateStamp(prj->date) ;
  if (ptrTime) {  
    CopyMem(prj->date, &(dt->dat_Stamp), sizeof(struct DateStamp)) ;
    dt->dat_Format = FORMAT_DOS ;
    dt->dat_StrTime = ptrTime ;
    DateToStr(dt) ;
    //CopyMem(ptrTime, prj->datestr, LEN_DATSTRING) ;
    DateToByte(ptrTime, prj) ;
  
  }
}

void processwin(idWin* prj) {
  /* variables
   */
  ULONG signals = NULL,                                                                          /* masque des signaux a attendre */
        mask,
        class,                                                                                                                   /* masque des signaux recus */
        sigtimer ;
        
  BOOL  stop    = FALSE ;                                                                                                                /* vrai si ctrl c */
  struct IntuiMessage * msg ;                     /* ptr sur message intuition */
  struct MsgPort      * extPort ;
  struct backMsg      * extmsg ;
  
  extPort = CreateMsgPort() ;
  extPort->mp_Node.ln_Name = AllocVec(10, MEMF_PUBLIC) ;
  CopyMem("backclock", extPort->mp_Node.ln_Name, 10) ;
  AddPort(extPort) ;
  
  sigtimer =  (1<<(prj->treq->tr_node.io_Message.mn_ReplyPort->mp_SigBit)) ; 
  /* signaux d'attentes
   */
  signals = SIGBREAKF_CTRL_C | 
            (1<<(prj->notifyPort->mp_SigBit)) | 
            (1<<(prj->win->UserPort->mp_SigBit)) | sigtimer|
            (1<<(extPort->mp_SigBit)) ;
  
  runtimer(prj,1) ;
  getDate(prj) ;
  effacer(prj) ;
  retracer(prj) ;
  while(!stop) {
    mask = Wait(signals) ;
    if (mask & SIGBREAKF_CTRL_C) {
      /* recu le signal CTRL C
       */
      stop=TRUE;
    }
    if (mask & (1<<(extPort->mp_SigBit))) {
      // recu message prog externe
      extmsg = (struct backMsg *)GetMsg(extPort) ;
      switch(extmsg->Class) {
        case BC_Quit:        // recu demande d'arret
          stop=TRUE ;
          extmsg->error = OK ;
          break;
      
        case BC_GetPrj:      // recu demande d'envoi du projet
          extmsg->ptrPrj = prj ;
          extmsg->error = OK ;
          break;
      
        case BC_RefreshColors:
          setColors(prj) ;
          break;
      
        case BC_Refresh:     // refresh window (redraw)
          reinit_win(prj) ;
          getDate(prj) ;
          effacer(prj) ;
          retracer(prj) ;
          extmsg->error = OK ;
          break;
      
        case BC_SaveConf:
          SaveEnv(prj, TRUE) ;
          if (prj->lastError) extmsg->error = prj->lastError ;
          break;
      
        case BC_UseConf:
          SaveEnv(prj, FALSE) ;
          if (prj->lastError) extmsg->error = prj->lastError ;
          break;
      
        case BC_SetWindow:
          getDate(prj) ;
          setWindow(prj) ;
          
          AbortIO((struct IORequest*)prj->treq) ;
          WaitIO((struct IORequest*)prj->treq) ;
          if(prj->backWin.drawsec) {
            
            runtimer(prj, 1) ;
          }
          extmsg->error = OK ;
          break;
        
        default:
          break;
      }
      if (extmsg) ReplyMsg((struct Message*)extmsg) ;
    }
    if (mask & (1<<(prj->notifyPort->mp_SigBit))) {
      // attention fermeture du WB
      if (partialClose(prj)) partialOpen(prj) ;
    }
    if (mask & 1<<(prj->win->UserPort->mp_SigBit)) {
      /* recu message d'intuition
       */
      while((msg = GT_GetIMsg(prj->win->UserPort)) != NULL) {
        /* retourne le message
         */
        class = msg->Class ;
        ReplyMsg((struct Message*)msg) ;
        if(class == IDCMP_CHANGEWINDOW) {
          
          RemoveGList(prj->win, &szgdg, 2) ;
          szgdg.Width = prj->win->Width ;
          tagdg.LeftEdge = prj->win->Width/2 ;
          tagdg.TopEdge  = prj->win->Height -20 ;
          tagdg.Width    = prj->win->Width /2 ;
          prj->backWin.width = prj->win->Width ;
          prj->backWin.height = prj->win->Height ;      
          prj->backWin.posX = prj->win->LeftEdge ;
          prj->backWin.posY = prj->win->TopEdge ;
          setWindow(prj) ;
          reinit_win(prj) ; 
          AddGList(prj->win, &szgdg, 0, 2, NULL) ;
          RefreshGList(&szgdg, prj->win, NULL, -1) ;

          SaveEnv(prj, TRUE) ;
        }  
      }          
    }
    if (CheckIO((struct IORequest*)prj->treq)) {
      WaitIO((struct IORequest*)prj->treq) ;
      AbortIO((struct IORequest*)prj->treq) ;
      WaitIO((struct IORequest*)prj->treq) ;
      getDate(prj) ;
      if(prj->backWin.drawsec)
        runtimer(prj, 1) ;
      else
        runtimer(prj, 60-(long)(prj->sec)) ;
      effacer(prj) ;
      retracer(prj) ;
      //WindowToBack(prj->win) ;
    }  
 
  }
  AbortIO((struct IORequest*)prj->treq) ;
  WaitIO((struct IORequest*)prj->treq) ;
  RemPort(extPort) ;
  FreeVec(extPort->mp_Node.ln_Name) ;
  DeleteMsgPort(extPort) ;
     
}

void ez_req(UBYTE * title, UBYTE * body, UBYTE * gadg, APTR arglist ) {
  struct EasyStruct * ez_rq ;
  
  if (ez_rq = AllocVec(sizeof(struct EasyStruct), MEMF_PUBLIC)) {
    if (ez_rq->es_Title = AllocVec(strlen(title)+1, MEMF_PUBLIC)) {
     strcpy(ez_rq->es_Title, title) ;
     if (ez_rq->es_TextFormat = AllocVec(strlen(body)+1, MEMF_PUBLIC)) {
      strcpy(ez_rq->es_TextFormat, body) ;
      if (ez_rq->es_GadgetFormat = AllocVec(strlen(gadg)+1, MEMF_PUBLIC)) {
       strcpy(ez_rq->es_GadgetFormat, gadg) ;
       ez_rq->es_StructSize = sizeof(EasyStruct) ;
       ez_rq->es_Flags = NULL ;
       EasyRequestArgs(NULL, ez_rq, NULL, arglist) ;
       FreeVec(ez_rq->es_GadgetFormat) ;
      }
      FreeVec(ez_rq->es_TextFormat) ;
     }
     FreeVec(ez_rq->es_Title) ;
    }
    FreeVec(ez_rq) ;
  }
}

