/* DELP.C */

#include <demo.g>
#include <demo.rsg>
#include <hwim.h>

#define TIME_FMT_FLAGS (PR_TIME_MONTH_NAME|PR_TIME_SUFFIX_NAME)

LOCAL_C VOID InitTimeObject(PR_DELP *self)
    {
    P_DAYSEC ds;
    SE_TIME_FORMAT fmt;

    ds.day=self->delp.rbuf.dayno;
    ds.sec=0;
    self->delp.time=f_new(CAT_DEMO_OLIB,C_TIME);
    p_send4(self->delp.time,O_TO_SET,SET_TIME_DAYSEC,&ds);
    fmt.flags=TIME_FMT_FLAGS;
    p_send4(self->delp.time,O_TO_SET_FORMAT,&fmt,TIME_FMT_FLAGS);
    }

LOCAL_C UINT SenseBufWidth(PR_DELP *self,TEXT *pb)
    {
    return(p_send4(self,O_LPR_SENSE_BUF_WIDTH,pb,p_slen(pb)));
    }

LOCAL_C VOID FindWidthFirstColumn(PR_DELP *self)
    {
    INT i;
    TEXT buf[E_MAX_DAY_NAME];
    UWORD wid;

    for (i=0; i<7; i++)
        {
        p_nmday(&buf[0],i);
        wid=SenseBufWidth(self,&buf[0]);
        if (wid>self->delp.colwid)
            self->delp.colwid=wid;
        }
    self->delp.colwid+=SenseBufWidth(self,"  ");    /* two spaces */
    if (self->delp.colwid>(3*self->lprinter.width/4))
        {
        hInfoPrint(DELP_PAPER_NARROW);
        p_sleep(20);
        p_leave(RUN_ACTIVE_CLEANUP_NONOTIFY);
        }
    self->lprinter.subsqind=self->delp.colwid;
    }

#pragma METHOD_CALL

METHOD VOID delp_lpr_init(PR_DELP *self,RBUF_LP *prbuf)
    {
    self->delp.rbuf=(*prbuf);
    p_supersend2(self,O_LPR_INIT);
    }

METHOD INT delp_lpr_sense_text(PR_DELP *self,WDR_PRINT *pr)
    {
    P_DATE dt;
    P_DAYSEC ds;

    if (!self->delp.time)
        {
        InitTimeObject(self);
        FindWidthFirstColumn(self);
        }
    else if (!self->delp.rbuf.ndays)
        return(FALSE);
    switch (self->delp.state++)
        {
    case DELP_STATE_COL1:
        if (self->delp.rbuf.gap)
            {
            p_send4(self->delp.time,O_TO_SENSE,SENSE_TIME_DATE,&dt);
            if (!dt.day)
                {
                pr->down=pr->height;
                if (self->delp.rbuf.gap==1)
                    pr->down>>=1;
                }
            }
        p_send4(self->delp.time,O_TO_SENSE,SENSE_TIME_DAYSEC,&ds);
        p_nmday(&self->delp.dname[0],P_WEEK(ds.day));
        self->delp.right=self->delp.colwid
                                -SenseBufWidth(self,&self->delp.dname[0]);
        pr->buf=(&self->delp.dname[0]);
        break;
    case DELP_STATE_COL2:
        pr->flags&=(~(WDR_PRINT_LINE|WDR_PRINT_TEXT));
        pr->flags|=WDR_PRINT_RIGHT;
        pr->right=self->delp.right;
        return(TRUE);
    case DELP_STATE_COL3:
        p_send4(self->delp.time,O_TO_SENSE,SENSE_TIME_DATESTR,&self->delp.buf[0]);
        pr->buf=(&self->delp.buf[0]);
        pr->flags&=(~WDR_PRINT_LINE);
        pr->indent=self->delp.colwid;
        self->delp.rbuf.ndays--;
        p_send4(self->delp.time,O_TO_ADD_DAYS,1,0);
        self->delp.state=DELP_STATE_COL1;
        }
    pr->blen=p_slen(pr->buf);
    return(TRUE);
    }
