# desc “Explaining what the task does” # task :skinny_forum do # # Task goes here # end

require 'csv'
@data_path = 'data/'

namespace :db do

  task(:load_forum => :environment){
    Xforum::Category.categories({none:0},Xforum.user_class.find_by(forum_admin:true))
    Xforum::Topic.topics({category:'select category'},Xforum.user_class.find_by(forum_admin:true))
    file_name='app_data/forum_base.csv'
    load_the_forum_file(file_name)
  }

  task(:load_help => :environment){
    Xforum::Category.categories({none:0},Xforum.user_class.find_by(forum_admin:true))
    Xforum::Topic.topics({category:'select category'},Xforum.user_class.find_by(forum_admin:true))
    file_name='app_data/forum_help.csv'
    load_the_forum_file(file_name)
  }
end

def  load_the_forum_file(file_name)
  CSV.foreach(file_name, headers: true) { |row|
    the_row=row.to_hash
    puts "'row ' #{the_row['topic']} , #{the_row['content']}"
    category_id=Xforum::Category.where(name:the_row['category']).pluck(:id)[0]
    category_id=Xforum::Category.create(name:the_row['category']).id if category_id.nil?
    topic_id=Xforum::Topic.where(name:the_row['topic']).pluck(:id)[0]
    topic_id=Xforum::Topic.create(name:the_row['topic'],category_id:category_id).id if topic_id.nil?
    the_row.delete('category')
    the_row.delete('topic')
    the_row.store(:topic_id,topic_id)
    Xforum::Forum.create(the_row)
  }
  topics=Xforum::Topic.all.pluck(:id)
  topics.each{|topic|
    list=xforum_named_array(Xforum::Forum.where(topic_id:topic).pluck(:id,:parent,:tag),[:id,:parent,:tag])
    list.each{ |comment|
      Xforum::Forum.where(parent:comment[:tag],needs_translating:false).update_all(parent:comment[:id],needs_translating:true)
    }
  }
  Xforum::Forum.all.update_all(needs_translating:false,tag:-1)
end

def xforum_named_array(data,params)
  data = Array.new(params.size,nil)  if data.nil? || data.empty?
  if  data.size==1
    double=true
    data.push(data[0])
  end
  pseudo= !data[0].is_a?(Array)
  temp=Array.new{{}}
  pseudo ? size=1 : size=data.size
  (0...size).each {|i|
    temp[i]={}
    datax=data[i]
    (0...params.size).each { |j|
      pseudo ? temp[i].store(params[j], data[j]) : temp[i].store(params[j], datax[j]) }
  }
  temp.shift if double
  temp
end