# -*- coding: utf-8 -*-
class ExcelController < ApplicationController
  
  # Авторизация (файл: controllers/application.rb)
  before_filter :isAuthorization
  
  def index
    info = params[:i]

    # Очищаем от сгенерированых файлов
    self.clearFiles()

    # CHecking...
    if(info.scan("<tr>").size>0 && info.scan("<td").size>0)

        info = info.gsub('<tbody>', '')
        info = info.gsub('</tbody>', '')
        info = info.gsub(/\<th\>.*\<\/th\>/im, '')

        # parsing ...
        temp = info.split(/\<tr[^>]{0,}\>/).compact

        # Format book
        require 'spreadsheet'
        Spreadsheet.client_encoding = 'UTF-8'
        book = Spreadsheet::Workbook.new
        dataBook1 = book.create_worksheet :name => 'book'

        # Data for book
        i=0
        for value in temp
          a=0
          value = value.gsub(/\s/im, '')
          if(value!=nil && value!="" && value.length.to_s!='0' && value.scan("<td").size>0)
            row = dataBook1.row(i)
            tds = value.split(/\<td[^>]{0,}\>/).compact
            for td in tds
              if(td.length.to_s!='0')
                td = td.gsub(/\<[^>]*?\>/im, '')
                #td = td.gsub(/\s/im, '')
                row[a] = ""+td+""
                a+=1
              end
            end
            i+=1
          end
        end

        # Write book
        @file = 'excel-' + rand().to_s + '.xls'
        book.write 'public/'+@file
    else
      @file='false'
    end
 end




  def clearFiles
    # Получаем все сгенерированные файлы
    files = Dir.glob("public/*.xls")
    # Время сейчас
    time = Time.new
      for file in files
      # Время через 5 мин
      fileData = File.mtime(file).since(300)

          if(fileData<Time.now)
            File.delete(file)
          end
      end
  end

end
