#!/usr/local/bin/ruby
# -*- Ruby -*-
# mhc2pscal : a wrapper for pscalj.sh
# Composed by OHARA Shigeki <oharakun@hauN.org>

Usage = "% #{$0} <month> <year>"

require 'mhc-schedule'
require 'kconv'

unless (ARGV.size == 2)
  STDERR.puts Usage
  exit(1)
end

#category = '!MyTV'
category = nil

TmpFile = "mhc_holiday.tmp"
ENV['EFILE'] = TmpFile

PscalCmd = 'pscal'
PscalArgs = ['-t']

MM, YYYY = ARGV[0].to_i, ARGV[1].to_i

### SubRoutines

class String
  # digest a string upto max size.
  # when the bound is unsafe for muti-bytes, replace the character with '$'
  def digest (max, tail_adjust = '$', fill_up = nil)
    euc = (Kconv::toeuc(self))[0..max-1]

    if fill_up and euc.size < max
      return euc + fill_up * (max - euc.size)
    end

    is2byte = false
    euc.each_byte do |char|
      is2byte = ! is2byte if char & 0x80 == 0x80
    end

    if is2byte
      euc[max - 1] = tail_adjust
    end
    return euc
  end
end

def get_schedule(db, yyyy, mm, category)
  buffer_max = 18
  sch_max = 3

  ret = ''
  from = MhcDate.new(yyyy, mm, 1)
  to = MhcDate.new(yyyy, mm + 1, -1)

  db.search(from, to, category).each { |date, items|
    items[0..sch_max - 1].each { |sch|
      ret += format("%d:%d:%-11s\n", date.m, date.d, sch.time_as_string)
      ret += format("%d:%d:  %s\n", date.m, date.d,
		    sch.subject.digest(buffer_max))
    }
    if sch_max < items.size
      ret += format("%d:%d:※続きあり！\n", date.m, date.d)
    end
  }
  return ret
end

### main

db = MhcScheduleDB.new

contents = get_schedule(db, YYYY, MM, category)

File::open(TmpFile, "w") { |f| f.print contents }
system("#{PscalCmd} #{PscalArgs.join(' ')} #{MM} #{YYYY}")
File::unlink(TmpFile)
