require "net/http"
require "uri"
require 'json'

namespace :upgrade do
  desc "Imports announcements from orbit 4.2"
  task :import_announcement,[:url] => :environment do |task,args|
  	puts "Starting to import announcments from #{args.url}"
  	uri = URI.parse("#{args.url}/panel/upgrade/module?module=announcement")
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri)
    response = http.request(request)
    data = JSON.parse(response.body) rescue nil
    if !data.nil? && data["success"] == true
    	puts "Importing categories...."
	    categories = data["categories"]
	    tags = data["tags"]
	    announcements = data["announcements"]
	    module_app = ModuleApp.find_by_key("announcement")
	    I18n.locale = :zh_tw
	    categories.each do |category|
	    	c = Category.where(:title => category["title"]["zh_tw"], :module_app_id => module_app.id).first 
	    	c = Category.where(:title => category["title"]["en"], :module_app_id => module_app.id).first if c.nil?
	    	if c.nil?
	    		c = Category.new
	    		c.title_translations = category["title"]
	    		c.disable = category["disable"]
	    		c.module_app_id = module_app.id
	    		c.save
	    	end
	    end
	    puts "Categories imported."
	    puts "Importing tags..."
	    tags.each do |tag|
	    	t = module_app.tags.where(:name => tag["name"]["zh_tw"]).first
	    	t = module_app.tags.where(:name => tag["name"]["en"]).first
	    	if t.nil?
	    		t = Tag.new
	    		t.name_translations = tag["name"]
	    		t.is_default = tag["is_default"]
	    		t.save
	    	end
	    end
	    puts "Importing tags completed."
	    puts "Importing announcements..."
	    announcements.each do |announcement|
	    	bulletin = Bulletin.new
	    	bulletin.email_sent = announcement["email_sent"]
	    	bulletin.email_sentdate = announcement["email_sentdate"]
	    	bulletin.other_mailaddress = announcement["other_mailaddress"]
	    	bulletin.public = announcement["public"]
	    	bulletin.postdate = announcement["postdate"]
	    	bulletin.deadline = announcement["deadline"]
	    	bulletin.subtitle_translations = announcement["subtitle"]
	    	announcement["text"]["en"] = smart_downloader(announcement["text"]["en"], args.url.chomp("/"))
	    	announcement["text"]["zh_tw"] = smart_downloader(announcement["text"]["zh_tw"], args.url.chomp("/"))
	    	bulletin.text_translations = announcement["text"]
	    	bulletin.title_translations = announcement["title"]
	    	bulletin.remote_image_url = announcement["image"]
	    	announcement["links"].each do |link|
	    		l = BulletinLink.new
	    		l.title_translations = link["title"]
	    		l.url = link["url"]
	    		l.bulletin = bulletin
	    		l.save
	    	end
	    	announcement["files"].each do |file|
	    		f = BulletinFile.new
	    		f.title_translations = file["title"]
	    		f.description_translations = file["description"]
	    		f.remote_file_url = file["file"]
	    		f.bulletin = bulletin
	    		f.save
	    	end
	    	category = module_app.categories.where(:title => announcement["category"]["zh_tw"]).first
	    	category = module_app.categories.where(:title => announcement["category"]["en"]).first if category.nil?
	    	bulletin.category = category
	    	announcement["tags"].each do |tag|
	    		t = module_app.tags.where(:name => tag["name"]["zh_tw"]).first 
	    		t = module_app.tags.where(:name => tag["name"]["en"]).first if t.nil?
	    		bulletin.tags << t
	    	end
	    	bulletin.approved = true
	    	bulletin.save
	    end
	    puts "Announcements imported successfully."
	else
		puts "Import has some problem."
	end
  end
end

def smart_downloader(data,url)
    @data = data
    @user = User.where(:user_name => "rulingcom").first
    excluded_extensions = ["php","/"]
    regex = /https?:\/\/[\S]+/
    # @links = URI.extract(@data) rescue []
    @links = @data.scan(regex) rescue []
    @links = @links.map{|link| link.chomp("\"") if (link.include?url rescue false)}.reject{|link| link.nil?}.uniq
    @links.each do |link|
      link = link.gsub("\&amp\;","&")
      temp = link.gsub(url,"")
      extension = temp.split(".").last rescue nil
      if (extension.nil? || excluded_extensions.include?(extension))
        @data = @data.sub(link,"#")
      else
        a = Asset.new
        a.remote_data_url = link
        a.title_translations = {"en" => a.data.filename, "zh_tw" => a.data.filename}
        if (a.save! rescue false)
          @user.assets << a
          @user.save
          link = link.gsub("&","\&amp\;")
          @data = @data.sub(link, a.data.url)
        end
      end
    end
    @data
  end