from __future__ import print_function

import fileinput
import re
import sys
from getopt import getopt


# -----------------------------------------------------------------------------

class Processor(object):
  options = ""
  long_options = []
  defaults = {}

  @classmethod
  def argparse(cls, a):
    of = getattr(cls, "options")
    lof = getattr(cls, "long_options")
    opts = getattr(cls, "defaults", {})
    o, a = getopt(a, of, lof)
    print(opts, o, a)
    opts.update((k.lstrip("-"), v) for k, v in o)
    return opts, a

  def __init__(self, params=None):
    if not params:
      params = sys.argv[1:]

    self.opts, self.args = self.argparse(params)
    log("params: {0!r}\nopts: {1!r}\nargs: {2!r}\n".format(params, self.opts, self.args))

    self.init()
    self.files = self.getfiles()
    log("files: {0!r}".format(self.files))

    self.input = fileinput.FileInput(self.files)

    self.curline = self.input.readline()
    #log("firstline: {0}".format(self.curline))
    while self.curline:
      self.curline = self.curline.rstrip("\r\n")
      log(" DBG: #{0:<8} {1}".format(self.lineno, self.curline))
      self.process(self.curline, self.lineno)
      self.curline = self.input.readline()
      #log("line: {0}".format(self.curline))

  def init(self):
    pass
  def getfiles(self):
    return self.args
  def process(self, line, i):
    print("i:{0}, line: '{1}'".format(i, line))

  @property
  def lineno(self):
    return self.input.lineno()
  @property
  def curfile(self):
    return self.input.filename(), self.input.filelineno()


# -----------------------------------------------------------------------------

class Cut(Processor):
  options = "f:d:"
  defaults = { "f": "1", "d": "\s+" }

  def init(self):
    self.delimre = re.compile(self.opts["d"])
    log(str(self.delimre))
    from spiralx.fieldparse import getfields
    self.fields = list(getfields(self.opts["f"]))
    log("  fields: {0!r}".format(self.fields))

  def process(self, l, idx):
    c = [p for i, p in enumerate(self.delimre.split(l)) if (i+1) in self.fields]
    log("split = {1!r}, c = {0!r}".format(c, self.delimre.split(l)))
    print(",".join(c))


# -----------------------------------------------------------------------------

class Grep(Processor):
  options = "s:c:b:"
  defaults = { "s": "\S+", "c": "0", "o": "I", "b": "0" }

  def init(self):
    #reopts = reduce(lambda c, v: c | getattr(re, v, 0), self.opts["o"], 0)
    reopts = re.I if self.opts["c"] in "0n" else 0
    self.matchre = re.compile(self.opts["s"], reopts)
    self.showblanks = self.opts["b"] not in "0n"
    log("  showblanks = {0}, re = {1}[{2}]".format(self.showblanks, self.matchre.pattern, self.matchre.flags))

  def process(self, line, idx):
    ml = self.matchre.findall(line)
    if len(ml) or self.showblanks:
      print(", ".join(ml))

# -----------------------------------------------------------------------------

if __name__ == "__main__":
  with open("out.log", "w", 0) as f:
    f.write("sys.argv = {0!r}\n".format(sys.argv))
  proc = Grep()

