# coding: utf-8
# ruby excelUtil TEXCELL
# 2017.05 Ver.1.00
require 'date'

class ExcelUtilt

   def initialize

      @arMDay = [
         [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ],
         [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
      ]
      @msecpday = 24 * 60 * 60 * 1000
   end

   # Excelのシリアル値(実数)->rubyのDateTime
   def fromOADateTime(dedt)

      ia = dedt.to_i
      ib = (dedt - ia) * 86400
      ih = (ib / 3600).to_i; ib -= ih * 3600
      im = (ib / 60).to_i; ib -= im * 60
      ic = ib * 10 + 5; is = (ic / 10).to_i
      if is == 60 then im += 1; is = 0 end
      if im == 60 then ih += 1; im = 0 end
      if ih == 24 then ih = 0 end
      dta = DateTime.jd(ia + 2415019,ih,im,is)
      return dta
   end

   # 年月日->Excelのシリアル値
   def toOADate(iy, im, id)

      dr = 0.0
      ir = 1
      iarDay = 0
      if ((iy % 4) == 0) && ((iy % 100) != 0 || (iy % 400) == 0)
         iarDay = 1
      end
      if ((iy >= 1) && (iy <= 9999) && (im >= 1) && (im <= 12) && (id >= 1) && (id <= @arMDay[iarDay][im]))
         for ia in 0..(im - 2)
            id += @arMDay[iarDay][ia]
         end
         ii = iy - 1
         # 693594 1/1/1 -> 1899/12/31 days
         dr = ii * 365 + (ii / 4) - (ii / 100) + (ii / 400) + id - 693594
         ir = 0
      end
      return ir, dr
   end

   # 時分秒->Excelのシリアル値
   def toOATime(ih, im, is, ims = 0)

      ir = 1
      da = 0.0
      if (ih < 24) && (im < 60) && (is < 60) && (ims < 1000)
         da = (ih * (60 * 60 * 1000) + im * (60 * 1000) + is * 1000 + ims).to_f / @msecpday
         ir = 0
      end
      return ir, da
   end

   # 年月日時分秒->Excelのシリアル値
   def toOADateTime(iy, imn, id, ih, imi, is, ims = 0)

      dr = 0
      ir, dd = toOADate(iy, imn, id)
      if ir == 0
         ir, dt = toOATime(ih, imi, is, ims)
         if ir == 0
            dr = dd + dt
         end
      end
      return ir, dr
   end

   # ******* RGB値を取得 iRed,iGreen,iBlue:0～255 *******
   def rgb(iRed, iGreen, iBlue)

      return (iBlue << 16) | (iGreen << 8) | iRed
   end

end
