#include <unistd.h>

#include "OLineDoc.h"
#include "OXTextView.h"

//----------------------------------------------------------------------

OLineDoc::OLineDoc() {
  prev = next = this;
  _w = _h = 0;
  lnlen = 0;
}

OLineDoc::~OLineDoc() {
  Clear();
}

OLineDoc * OLineDoc::InsertBefore(OLineDoc * l) {
  l->prev = prev;
  l->next = this;
  prev->next = l;
  prev = l;
  return l;
}

OLineDoc * OLineDoc::InsertAfter(OLineDoc * l) {
  l->prev = this;
  l->next = next;
  next->prev = l;
  next = l;
  return l;
}

void OLineDoc::SetCanvas(OXTextFrame * c)
{
  _style_server = c;
  _canvas = c;
  SetColor("white");
}

void OLineDoc::SetColor(char * color)
{
  _gc = _style_server->GetGC(color);
}

void OLineDoc::Clear() {
  delete chars;
  lnlen = 0;
}

int OLineDoc::Fill(char * buf) {
  int  cnt;
  char c, *src;
  char line[MAXLINESIZE], *dst;
  int lh = _gc->_font->ascent + _gc->_font->descent;

  src = buf;
  dst = line;
  cnt = 0;
  while (c = *src++) {
    if (c == 0x0D || c == 0x0A)
      break;
    else if (c == 0x09)
      do
        *dst++ = ' ';
      while (((dst-line) & 0x7) && (cnt++ < MAXLINESIZE-1));
    else
      *dst++ = c;
    if (cnt++ >= MAXLINESIZE-1) break;
  }
  *dst = '\0';
  chars = new char[strlen(line) + 1];
  strcpy(chars, line);
  lnlen = strlen(chars);
  _h = lh * (int)(lnlen / 80) + lh;
  _w = 80;
  return True;
}

int OLineDoc::LoadFile(FILE * file) {
  char buf[MAXLINESIZE];

  if (fgets(buf, MAXLINESIZE, file) != NULL) {
    Fill(buf);
    return True;
  } else
    return False;
}

void OLineDoc::Layout() {
  ll = ((_w = _style_server->GetDocWidth()) - (2 * MARGIN)) / 6;
  if (!ll) ll = 1;
  _h = _gc->_font->ascent + _gc->_font->descent;
  _h *= (1 + (int)(lnlen / ll));
}

void OLineDoc::DrawRegion(Display *dpy, Drawable d,
                          int x, int y, XRectangle *rect) {
  int i;
  GC gc = _gc->_gc;
  int ld = _gc->_font->ascent;
  int lh = ld + _gc->_font->descent;

  for(i = 0; i <= (int)(lnlen / ll); i++) {
    XDrawString(dpy, d, gc, x + MARGIN, y + i*lh + ld,
                chars+i*ll, (lnlen<ll*(i+1)) ? lnlen-ll*i : ll);
  }
}
