# encoding: utf-8 

namespace :nccu_data do
  desc "load nccu data from csv"
  task :setup_ut_list => :environment do
    require 'csv'
    CSV.foreach("vendor/built_in_modules/announcement/lib/ut_list_from_nccu_2012feb.csv") do |row|
      new_unit = UnitListForAnc.new(:order => row[0], :ut_code => row[1], :up_ut_code => row[2], :created_at => Time.now,:updated_at => Time.now)
      #    order,ut_code,up_tu_code,ut_zh_tw,ut_en
      new_unit.build_title :en => row[4], :zh_tw => row[3]
      new_unit.save
    end
  end

  task :setup_0918_announcement => :environment do
    def null_or_val(str)
      if str == "NULL" 
        return nil
      else
        if str.class == "String"
          return str.force_encoding("utf-8")
        else
          return str
        end
      end
       
    end

    require 'csv'
    Bulletin.destroy_all
    to_this_category = BulletinCategory.first({conditions:{key: 'Announcement'}})
    counter = 0 
    CSV.foreach("vendor/built_in_modules/announcement/lib/nccu_ann20120918.csv") do |row|
        #bul_h1,bul_content,bul_ENh1,bul_ENcontent,bul_date,bul_deadline
        data = {:title_translations=>{:zh_tw=>(null_or_val(row[0])  rescue nil),:en=>(null_or_val(row[2])  rescue nil)},
                    :text_translations=>{:zh_tw=>(null_or_val(row[1])  rescue nil),:en=>(null_or_val(row[3])  rescue nil)},
                    :postdate=>(Date.parse(row[4])  rescue nil),
                    :deadline=>(Date.parse(row[5])  rescue nil), 
                    :bulletin_category_id=>to_this_category.id }
      if counter >=1
        Bulletin.create!(data.merge({:is_checked=> true,:is_pending=>false}))
      end
      counter+=1
    end
     Bulletin.all.each{|t| t.save}
  end
end