#coding: utf-8
require "./config/environment"

conn = Mysql2::Client.new(:host=>'localhost', :username=>'root', :password=>'111111', :database=>'sns')
conn2 = Mysql2::Client.new(:host=>'localhost', :username=>'root', :password=>'111111', :database=>'blog')

namespace :blog do
  desc "从旧有的博客迁移进来数据"
  task :convert do
    #导入用户数据
    members = conn.query("select * from uchome_member order by uid asc")
    members.each do |member|
      conn2.query("replace into users (`id`, `name`, password_digest, created_at, updated_at)
                   values ('#{member['uid']}', '#{member['username'].gsub("'", "\\\\'")}', '123', '#{Time.now}', '#{Time.now}')")
      user = User.find(member["uid"])
      boke = user.create_boke(:title => "#{user.name}的博客", :username => "#{user.name}", :signature=>'', :mostview=>'')
      if not boke
        puts user.name
      end
    end
    puts '导入用户数据完毕'

    #导入每个博客下的内容
    Boke.all.each do |boke|
      #查询用户的分类,导入分类
      cate_hash = {0=>boke.categories.first.id}
      classes = conn.query("select * from uchome_class where uid='#{boke.user_id}' order by classid asc")
      classes.each do |clas|
        category = boke.categories.create(:name=>clas["classname"])
        cate_hash[clas["classid"]] = category.id
      end

      #查询用户的文章,导入文章
      blogs = conn.query("select b.*, f.* from uchome_blog b left join uchome_blogfield f on b.blogid=f.blogid where b.uid='#{boke.user_id}' and b.friend in (0,1) order by b.blogid asc")
      blogs.each do |blog|
        article = boke.articles.create(:content_type=>1, :title=>blog["subject"], :content=>blog["message"], :views=>blog["viewnum"], :category_id=>cate_hash[blog["classid"]] ,:user_id=>boke.user_id, :created_at=>Time.at(blog["dateline"]))
        replies = conn.query("select * from uchome_comment where idtype='blogid' and id='#{blog["blogid"]}' and authorid>0 order by cid asc")
        replies.each do |reply|
          article.comments.create(:content=>reply["message"], :user_id=>reply["authorid"], :boke_id=>boke.id, :created_at=>Time.at(reply["dateline"]))
        end
      end
    end
    puts '导入文章完毕'

    #重设所有用户的密码
    #User.all.each do |user|
    #  user.update_attribute(:password, '123')
    #end
    #puts '重设密码完毕'

    #清除不存在的用户的评论
    conn2.query("delete from comments where user_id not in (select id from users)")
  end

  #desc "加入附件"
  #task :attach do
  #  articles = Article.all
  #  articles.select! do |article|
  #    #regexp = %r{<a href=["']?(attachment|http://ftphi.bccn.net).*?["']?.*?>}
  #    regexp = %r{<img src=["']?(attachment|http://ftphi.bccn.net).*?["']?.*?>}
  #    article.content =~ regexp
  #  end
  #  puts articles.size
  #end
end