/*------------------------------------------------------------------------------
 src/lib/dj/seq.cxx
 
 Copyright (c) 2004-2006 Darby Johnston.
 All rights reserved.
 Use is subject to license terms.
------------------------------------------------------------------------------*/

//#define DJ_DBG
#include "djSeq.h"
#include <djMath.h>
#include <stdio.h>

namespace dj {

Seq::Seq() : _start(0), _end(0), _pad(0) {}
Seq::Seq(int start, int end, int pad) { set(start, end, pad); }

void Seq::set(int start, int end, int pad)
{
  _start = start;
  _end = end;
  _pad = pad;
}

const Str toStr(const Seq & in)
{
  DJ_DBG_FNC("dj::toStr(Seq)");
  DJ_DBG_PRN("in = " << in);
  
  Str out = frameToStr(in.start(), in.pad());
  if (in.start() != in.end()) {
    out += '-';
    out += frameToStr(in.end(), in.pad());
  }

  DJ_DBG_PRN("out = " << out);
  return out;
}

const Seq toSeq(const Str & in)
{
  DJ_DBG_FNC("dj::toSeq(Str)");
  DJ_DBG_PRN("in = " << in);

  int start = 0, end = 0, pad = 0;
  const int size = in.size();
  if (size > 0) {
    const int i = find(in, '-');
    DJ_DBG_PRN("index = " << i);
    if (i >= 0) {
      int tmp;
      start = toFrame(cut(in, 0, i), &tmp);
      pad = max(tmp, pad);
      end = toFrame(cut(in, i + 1, size - i - 1), &tmp);
      pad = max(tmp, pad);
    } else {
      start = end = toFrame(in, &pad);
    }
  }

  Seq out(start, end, pad);
  DJ_DBG_PRN("out = " << out);
  return out;
}

const Str frameToStr(int in, int pad)
{
  char format [] = "%00d";
  static const int formatMax = 9;
  format[2] = char('0' + min(pad, formatMax));
  char tmp [DJ_CSTR_SIZE];
  const int size = snprintf(tmp, DJ_CSTR_SIZE, format, in);
  return Str(tmp, size);
}

int toFrame(const Str & in, int * pad)
{
  if (pad) {
    *pad = 0;
    const int size = in.size();
    if (size > 1) if (in[0] == '0') *pad = size;
  }
  return toInt(in);
}

Dbg & operator << (Dbg & dbg, const Seq & in)
{
  return dbg << in.start() << "-" << in.end() << "," << in.pad();
}

}
