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

module Admin::CustomAnnouncementsHelper
  def back_end_breadcrumb
    if params[:controller] == "admin/custom_announcements"
      res = ''
      divider = "<span class='divider'>/</span>"
      res << "<li><a href='#{admin_dashboards_path}'>#{t(:dashboard_)}</a>#{divider}</li>"
      if params[:custom_module]
        trans_name = I18n.t("module_name.#{params[:custom_module]}")
        if trans_name.include?("translation missing")
          trans_name = params[:custom_module]
        end
        res << "<li><a href='/admin/#{params[:custom_module].pluralize}'>#{trans_name}</a>#{divider}</li>"
      end
      if params[:action] != "index"
        if params[:custom_module]
          extra_url = "/#{params[:custom_module]}#{params[:bind_uid].present? ? ('-'+params[:bind_uid]) : ''}"
        end
        res << "<li><a href='/#{params[:controller]}#{extra_url}'>#{t('module_name.'+@module_app.key)}</a>#{divider}</li>"
        res << "<li class='active'>#{t(params[:action], scope: 'restful_actions')}</li>"
      else
        res << "<li>#{t('module_name.'+@module_app.key)}</li>"
      end
      res.html_safe
    else
      super
    end
  end
  def page_for_custom_bulletin(custom_bulletin)
    ann_page = nil
    pages = Page.where(:module=>'custom_announcement')

    pages.each do |page|
      if page.categories.count ==1
        if page.categories.include?(custom_bulletin.category.id.to_s)
          ann_page = page
        end
      end
      break if !ann_page.nil?
    end

    if ann_page.nil?
       pages.each do |page|
        if (page.categories.include?(custom_bulletin.category.id.to_s) rescue false)
          ann_page = page
        end
        break if !ann_page.nil?
      end
    end

    ann_page = pages.first if ann_page.nil?
    (ann_page.get_url+'/'+custom_bulletin.to_param).gsub('//','/') rescue "#"
  end

  def import_this_custom_announcement(row,categories,tags)
    value = {}
    custom_anns = CustomBulletin.new
    row.cells.each_with_index do |cell,index|
      val = cell.value rescue nil
      if [8,9,10,11,12,13,14,15].exclude?(index)
        next if val.blank?
      end
      case index
      when 0
        custom_anns.category = categories[val.to_i]
      when 1
        new_tags = []
        if (val.include?(",") rescue false)
          ts = val.split(",")
          ts.each do |t|
            new_tags << tags[t.to_i]
          end
        else
          new_tags << tags[val.to_i]
        end
        custom_anns.tags=new_tags
      when 2
        custom_anns.postdate = val
      when 3
        custom_anns.deadline = val
      when 4
        custom_anns.is_top = (val.to_i == 1 ? true : false)
      when 5
        custom_anns.is_hot = (val.to_i == 1 ? true : false)
      when 6
        custom_anns.is_hidden = (val.to_i == 1 ? true : false)
      when 7
        custom_anns.remote_image_url = val
      when 8
        value["en"] = val
      when 9
        value["zh_tw"] = val
        custom_anns.image_description_translations = value
        value = {}
      when 10
        value["en"] = val
      when 11
        value["zh_tw"] = val
        custom_anns.title_translations = value
        value = {}
      when 12
        value["en"] = val
      when 13
        value["zh_tw"] = val
        custom_anns.subtitle_translations = value
        value = {}
      when 14
        value["en"] = val
      when 15
        value["zh_tw"] = val
        custom_anns.text_translations = value
        value = {}
      when 16
        links = val.split(";") rescue []
        desc_en = row.cells[17].value.split(";") rescue []
        desc_zh_tw = row.cells[18].value.split(";") rescue []
        links.each_with_index do |link,i|
          bl = CustomBulletinLink.new
          bl.url = link.strip
          bl.title_translations = {"en" => desc_en[i], "zh_tw" => desc_zh_tw[i]}
          bl.custom_bulletin_id = custom_anns.id
          bl.save
        end
      when 19
        files = val.split(";") rescue []
        desc_en = row.cells[20].value.split(";") rescue []
        desc_zh_tw = row.cells[21].value.split(";") rescue []
        alt_en = row.cells[22].value.split(";") rescue []
        alt_zh_tw = row.cells[23].value.split(";") rescue []
        files.each_with_index do |file, i|
          bf = CustomBulletinFile.new
          bf.remote_file_url = file.strip rescue nil
          bf.title_translations = {"en" => (desc_en[i] rescue ""), "zh_tw" => (desc_zh_tw[i] rescue "")}
          bf.description_translations = {"en" => (alt_en[i] rescue ""), "zh_tw" => (alt_zh_tw[i] rescue "")}
          bf.custom_bulletin_id = custom_anns.id
          bf.save
        end
      end
    end
    custom_anns.create_user_id = current_user.id.to_s
    custom_anns.update_user_id = current_user.id.to_s
    custom_anns.approved = true
    custom_anns.save
  end

  def send_rejection_email(custom_announcement,locale)
    user = User.find(custom_announcement.create_user_id) rescue nil
    if !user.nil?
      email = user.member_profile.email
      if !email.nil? && email != ""
        url = "http://#{request.host_with_port}/admin/custom_announcements/#{custom_announcement.id}/edit"
        datatosend = "<h3>Hello #{user.name},</h3><p>#{current_user.name} #{t("custom_announcement.rejected_annoucement")} : #{custom_announcement.rejection_reason} <a href='#{url}'> #{t("custom_announcement.click_here_to_see")}</a></p>"
        mail = Email.new(:mail_to => email, :mail_subject => "CustomAnnouncement rejected公告未通過 : #{custom_announcement.title_translations[locale]}.", :template => "email/custom_announcement_email.html.erb", :template_data => {"html" => datatosend})
        mail.save
        mail.deliver rescue nil
      end
    end
  end

  def send_notification_mail_to_managers(custom_announcement, type, locale)
    users = []
    if @custom_announcement_setting.email_to.include?("managers")
      authorizations = Authorization.where(:module_app_id => @module_app.id)
      users = authorizations.collect do |auth|
        auth.user
      end
    end
    if @custom_announcement_setting.email_to.include?("admins")
      wg = Workgroup.where(:key => "admin").first
      admins = User.where(:workgroup_id => wg.id)
      users.delete(nil)
      users = users.concat(admins.to_a)
    end
    if @custom_announcement_setting.email_to.include?("approvers")
      approvers = User.find(@custom_announcement_setting.approvers).to_a rescue []
      auths = Authorization.where(:category_id => custom_announcement.category_id).collect{|a| a.user}
      users = users.concat(approvers & auths)
    end
    users.each do |user|
      email = user.member_profile.email
      if !email.nil? && email != ""
        send_email(user.name, email, custom_announcement, type, locale)
        # sleep(1)
      end
    end
  end

  def send_email(name, useremail, custom_announcement, type, locale)
    url = "http://#{request.host_with_port}/admin/custom_announcements?url=#{page_for_custom_bulletin(custom_announcement).sub("http://" + request.host_with_port, "")}&id=#{custom_announcement.id}"

    case type
    when "approval"
      datatosend = "<h3>#{t("custom_announcement.approval_mail_hi", :name => name)},</h3><p>#{t("custom_announcement.submitted_new_custom_announcement", :poster => current_user.name)}<br /><br />#{t("custom_announcement.approval_custom_announcement_title")} : #{custom_announcement.title_translations[locale]} <br /> #{t("custom_announcement.click_here_to_see")} : <a href='#{url}'> #{url} </a></p>"
    when "reapproval"
      datatosend = "<h3>#{t("custom_announcement.approval_mail_hi", :name => name)},</h3><p>#{t("custom_announcement.updated_annoucement", :poster => current_user.name)}<br /><br />#{t("custom_announcement.approval_custom_announcement_title")} : #{custom_announcement.title_translations[locale]} <br /> #{t("custom_announcement.click_here_to_see")} : <a href='#{url}'> #{url} </a></p>"
    end
    email = Email.new(:mail_to => useremail, :mail_subject => " #{t("custom_announcement.custom_announcement_subject")} : #{custom_announcement.title_translations[locale]}.", :template => "email/custom_announcement_email.html.erb", :template_data => {"html" => datatosend})
    email.save
    email.deliver rescue nil
  end

  def download_tmp_xml(url)
    xml = File.join(Rails.root, "tmp", "ann_cc_ntu.xml")
    open(xml, 'wb') do |fo|
      fo.print open(url).read
    end
  end

  def import_from_tmp_xml(file)
    xml = Nokogiri::XML(file)
    return if xml.nil?
    custom_announcements = []
    xml.xpath("//channel").xpath("//item").each do |custom_anns|
      custom_announcements << {
        :title => (custom_anns>"title").text,
        :category => (custom_anns>"category").text,
        :postdate => (custom_anns>"pubDate").text,
        :text => (custom_anns>"description").text,
        :rss2_sn => (custom_anns>"link").text.split("=").last
      }
    end
    custom_announcements.each do |custom_anns|
      ma = ModuleApp.where(:key => "custom_announcement").first
      cat = Category.where(:title => custom_anns[:category]).first rescue nil
      if cat.nil?
        cat = Category.create(:title_translations => {"en" => custom_anns[:category], "zh_tw" => custom_anns[:category]}, :module_app_id => ma.id)
      end
      ann = CustomBulletin.where(:rss2_sn => custom_anns[:rss2_sn]).first rescue nil
      if ann.nil?
        ann = CustomBulletin.new(:title_translations => {"en" => "", "zh_tw" => custom_anns[:title]}, :postdate => custom_anns[:postdate], :subtitle_translations => {"en" => "", "zh_tw" => custom_anns[:title]}, :text_translations => {"en" => "", "zh_tw" => custom_anns[:text]}, :rss2_sn => custom_anns[:rss2_sn], :category_id => cat.id, :approved => true, :create_user_id => current_user.id)
      else
        ann.update_attributes(:title_translations => {"en" => "", "zh_tw" => custom_anns[:title]}, :postdate => custom_anns[:postdate], :subtitle_translations => {"en" => "", "zh_tw" => custom_anns[:title]}, :text_translations => {"en" => "", "zh_tw" => custom_anns[:text]})
      end
      ann.save
    end
    File.delete(file)
  end

  def import_from_wordpress(xmlfile)
    xml_file = File.read(xmlfile)
    doc = Nokogiri::XML.parse(xml_file)

    doc.xpath("//channel").each do|channel_data|
      channel_data.xpath('//item').each  do|itme|

        bu = CustomBulletin.where(:rss2_sn =>  itme.xpath('wp:post_id').text ).first rescue nil
        if bu.nil?
            bu = CustomBulletin.new
            bu.approved = true
            bu.rss2_sn            = itme.xpath('wp:post_id').text
            bu.title_translations = {"en" => itme.xpath('title').text, "zh_tw" => itme.xpath('title').text}
            bu.text_translations  = {"en" => itme.xpath('content:encoded').text, "zh_tw" => itme.xpath('content:encoded').text}
            bu.postdate           = itme.xpath('wp:post_date').text

            itme.xpath('category').each do |i_cate|
              if i_cate["domain"].to_s == "category"

                  cat = @module_app.categories.where(:title => i_cate.text.to_s).first rescue nil
                  if cat.nil?
                    cat = Category.new
                    cat.module_app  = @module_app
                    cat.title_translations = {"en" => i_cate.text.to_s, "zh_tw" => i_cate.text.to_s}
                    cat.save
                  end
                  bu.category = cat

              elsif i_cate["domain"].to_s == "post_tag"

                  tag = Tag.where(:name =>  i_cate.text.to_s ).first rescue nil
                  if tag.nil?
                    tag = Tag.new
                    tag.name_translations = {"en" => i_cate.text.to_s, "zh_tw" => i_cate.text.to_s}
                    tag.module_app_ids << @module_app.id
                    tag.save
                  end

                  bu.tags = tag
              end
            end

        bu.save
        end

      end
    end
    File.delete(xmlfile)
  end

  def load_access_level
    if (current_user.is_admin? rescue false)
      @access_level = "admin"
    elsif (current_user.is_manager?(@module_app) rescue false)
      @access_level = "manager"
    else
      @access_level = "users"
    end
  end

  def user_can_approve?(custom_anns=nil)
    can_approve = false
    setting = CustomAnnouncementSetting.first
    case @access_level
    when "admin"
      can_approve = true
    when "manager"
      can_approve = true
    else
      can_approve = false
    end
    if !can_approve
      if !custom_anns.nil?
        if setting.approvers.include?(current_user.id.to_s)
          if (current_user.approved_categories_for_module(@module_app).include?(custom_anns.category) rescue false)
            can_approve = true
          end
        end
      else
        can_approve = setting.approvers.include?(current_user.id.to_s)
      end
    end
    can_approve
  end

end
