class CustomAnnouncementsController < ApplicationController
  include CustomAnnouncementsHelper
  def comment
    @custom_bulletin = CustomBulletin.where(:uid=>params[:uid]).first
    comment_val = params['comment']
    if !@custom_bulletin.nil? && @custom_bulletin.open_comment_for_user(OrbitHelper.current_user) && !comment_val.blank?
      account_id = OrbitHelper.current_user.member_profile.id.to_s rescue 'visitor'
      b = CustomBulletinComment.new(ip: request.remote_ip,comment: comment_val,account_id: account_id)
      b.custom_bulletin_id = @custom_bulletin.id
      b.save
      render :json => {}
    end
  end
  def index
    CustomBulletin.remove_expired_status
    sorted,total_pages = get_sorted_annc
    sorted = [] if sorted.nil?
    custom_anns = sorted.collect do |a|
      if a["source-site"].blank?
        statuses = a.statuses_with_classname.collect do |status|
          {
            "status" => status["name"],
            "status-class" => "status-#{status['classname']}"
          }
        end
        locale = OrbitHelper.get_site_locale.to_s
        files = a.custom_bulletin_files.map{|file|  { "file_url" =>  file.file.url + "\" title=\"#{file.file_title}", "file_title" => (file.title.blank? ? File.basename(file.file.path) : file.title rescue '') } if file.enabled_for?(locale) } rescue []
        files.delete(nil)
        links = a.custom_bulletin_links.map{|link|  { "link_url" => link.url, "link_title" => (link.title.blank? ? link.url : link.title) } } rescue []
        author = User.find(a.create_user_id).member_profile.name rescue ""
        desc = a.image_description
        desc = (desc.blank? ? "custom_announcement image" : desc)
        link_to_show = a.is_external_link ? a.external_link :  OrbitHelper.url_to_show(a.to_param)
        target = a.is_external_link ? "_blank" : "_self"
        doc = Nokogiri::HTML(a.title)
        title = doc.text.empty? ? 'no content' : doc.text
        {
          "department" => author,
          "custom_bulletin_links" => links,
          "custom_bulletin_files" => files,
          "title" => a.title,
          "source-site" => "",
          "source-site-title" => "",
          "source-site-link" => "",
          "subtitle" => a.subtitle,
          "statuses" => statuses,
          "category" => (a.category.title rescue ''),
          "postdate" => a.postdate,
          "author" => author,
          "is_top" => (a.is_top? ? 1 : 0),
          "link_to_show" => link_to_show+"\" title=\"#{title}\"",
          "target" => target,
          "img_src" => a.image.thumb.url || "/assets/custom_announcement-default.jpg",
          "img_description" => desc,
          "more" => t(:more_plus),
          "view_count" => a.view_count
        }
      else
        a
      end
    end
    #If no data , hide title&table
    if sorted.count == 0
      display = "hide"
    end
    # custom_anns = custom_anns.concat(feeds_custom_anns)
    # total_pages = custom_announcements.total_pages
    params = OrbitHelper.params
    page = Page.where(url:params['url']).first
    @annc_page_title = nil
    if (params['category'] != page.categories rescue true)
      @annc_page_title = Category.find(Array(params['category']).first).title rescue nil
    end
    if (params["tags"] != page.tags && !params["tags"].blank? && params["tags"].count == 1 && params["tags"][0] != "all" rescue true)
      @annc_page_title = Tag.find(Array(params['tags']).first).name rescue nil
    end
    {
      "custom_announcements" => custom_anns,
      "extras" => {
        "widget-title" =>t('custom_announcement.custom_announcement'),
        "title-head" => t('custom_announcement.table.title'),
        "date-head" => t('custom_announcement.table.date'),
        "status-head" => t('custom_announcement.table.status'),
        "author-head" => t('custom_announcement.table.author'),
        "subtitle-head" => t('custom_announcement.table.sub_title'),
        "category-head" => t('custom_announcement.table.category'),
        "link-head" => t('custom_announcement.table.link'),
        "file-head" => t('custom_announcement.table.file'),
        "view-count-head" => t('custom_announcement.table.view_count'),
        "display" => display,
        "department-head" => t('custom_announcement.table.department'),
        "page-title" => @annc_page_title
      },
      "total_pages" => total_pages
    }

  end
  def self.custom_widget_data
    @custom_configs = CustomBulletinConfig.all.to_a
    ac = ActionController::Base.new
    ac.render_to_string("custom_announcements/custom_widget_data",:locals=>{:@custom_data_field=>@custom_data_field,:@custom_configs=>@custom_configs,:@field_name=>@field_name})
  end
  def random_custom_announcement_widget
    pack_data(true)
  end

  def widget
    pack_data()
  end

  def tag_cloud
    ma = ModuleApp.where(:key => "custom_announcement").first
    temp = []
    ma.tags.each do |tag|
      t1 = tag.taggings.collect{|t| t.taggable_id.to_s}
      count = CustomBulletin.where(:id.in => t1).can_display_and_sorted.count
      temp << {
        "tag-name" => tag.name,
        "count" => count,
        "tag-url" => OrbitHelper.widget_more_url + "?tags[]=" + tag.id.to_s
      }
    end
    max = temp.max_by{|t| t["count"]}["count"]
    tags = []
    temp.each do |tag|
      if tag["count"] > 0
        percent = (tag["count"] * 100) / max
        font_size = ((percent / 10).round) + 16
        tag["font-size"] = font_size
        tags << tag
      end
    end
    {
      "tags" => tags,
      "extras" => {}
    }
  end

  def pack_data(is_random=false)
    cats = OrbitHelper.widget_categories || []
    tags = OrbitHelper.widget_tags || []
    subpart = OrbitHelper.get_current_widget
    custom_data_field = subpart.custom_data_field
    get_tabs_option
    custom_anns = []
    use_tag = false
    if @tab_option == 0
      custom_anns = get_anncs_for_pack_data(cats,tags,nil,is_random)
    else
      if cats.count != 1 || tags == ["all"]
        cats.each do |cat|
          custom_anns = custom_anns + get_anncs_for_pack_data([cat],tags,'')
        end
      else
        tags.each do |tag|
          custom_anns = custom_anns + get_anncs_for_pack_data(cats,[tag],tag)
        end
        use_tag = true
      end
    end
    mp = (custom_anns[0]["img_src"] rescue "")
    mpd = (custom_anns[0]["img_description"] rescue "")
    if @tab_option == 1
      if use_tag
        tags = ["all"] + tags
      else
        cats = ["all"] + cats
      end
      custom_anns = custom_anns.sort{|v1,v2| v2["postdate"]<=>v1["postdate"]}
    end
    cats = cats.uniq
    tags = tags.uniq
    tags_translations = tags.map{|tag_id|
      if tag_id == "all"
        t = I18n.t(:all)
      else
        t = Tag.find(tag_id).name rescue ""
      end
      [tag_id,t]
    }.to_h
    cats_translations = cats.map{|cat_id| 
      if cat_id == "all"
        t = I18n.t(:all)
      else
        t = Category.find(cat_id).title rescue ""
      end
      [cat_id,t]
    }.to_h
    cats_relations = cats_translations.map{|cat_id,t| 
      if cat_id == "all"
        t = "all"
      end
      [cat_id,t]
    }.to_h
    page = OrbitHelper.page.find_page(:page_id=> subpart.read_more_page_id).first rescue nil
    page = OrbitHelper.page.find_page(:module => "custom_announcement").first rescue nil if page.nil?
    all_cats = cats.dup
    all_cats.delete "all"
    if all_cats.count == 0
      all_cats = ["all"]
    end
    all_tags = tags.dup
    all_tags.delete "all"
    if all_tags.count == 0
      all_tags = ["all"]
    end
    max_all_count = [OrbitHelper.widget_data_count,custom_anns.count].min
    if @tab_option != 0
      OrbitHelper.set_widget_title(OrbitHelper.widget_title + 
        "<div style=\"clear: both;\"></div>" +
        "<ul class=\"nav_tabs_filter\">" +
          (use_tag ? tags.map.with_index{|tag,i|
            read_more_url = "/#{I18n.locale.to_s + page.url}" rescue ""
            read_more_url = read_more_url + "?" + {"category"=>all_cats,"tags"=>(tag == 'all' ? all_tags : [tag])}.to_param if read_more_url != ""
            read_more_text = I18n.t("custom_announcement.more")
            if tag != "all"
              begin
                read_more_text = I18n.t("custom_announcement.more_") + tags_translations[tag]
              rescue 
                nil
              end
            end
            "<li class=\"filter_tab#{i == 0 ? ' active' : ''}\" #{(tag == 'all' && @all_setting_option == 0) ? "data-count_limit=\"#{max_all_count}\"" : ''} data-read_more_text=\"#{read_more_text}\" data-read_more=\"#{read_more_url}\" data-tags=\"#{tag}\">#{tags_translations[tag]}</li>"
          }.join("") : cats.map.with_index{|cat,i|
            read_more_url = "/#{I18n.locale.to_s + page.url}" rescue ""
            read_more_url = read_more_url + "?" + {"category"=>(cat == 'all' ? all_cats : cat)}.to_param if read_more_url != ""
            read_more_text = I18n.t("custom_announcement.more")
            if cat != "all"
              begin
                read_more_text = I18n.t("custom_announcement.more_") + cats_translations[cat]
              rescue 
                nil
              end
            end
            "<li class=\"filter_tab#{i == 0 ? ' active' : ''}\" #{(cat == 'all' && @all_setting_option == 0) ? "data-count_limit=\"#{max_all_count}\"" : ''} data-read_more_text=\"#{read_more_text}\" data-read_more=\"#{read_more_url}\" data-category=\"#{cats_relations[cat]}\">#{cats_translations[cat]}</li>"
          }.join("")) +
        "</ul>"
      )
      filter_attr = (use_tag ? 'data-tags' : 'data-category')
      extra_html = '
      <script>
        if(typeof(wpexAnimsition) == "undefined"){
          var wpexAnimsition = {
            "loading":"1",
            "inDuration":"400",
            "outDuration":"400",
            "inClass":"fade-in",
            "outClass":"fade-out",
            "need_fix_containers":".widget-custom_announcement-4,.widget-custom_announcement-15",
            "linkElement": "[data-list=\"custom_announcements\"] > *",
            "children_text_block": ".w-annc__content-wrap",
            "container_block": "[data-subpart-id=\"'+subpart.id.to_s+'\"] [data-list=\"custom_announcements\"]:not(tbody)",
            "parent_block": "[data-subpart-id=\"'+subpart.id.to_s+'\"]",
            "filter_bar": ".nav_tabs_filter",
            "filter_option": "li.filter_tab",
            "filter_attr": "'+filter_attr+'",
            "filter_target_attr": "class",
            "use_attr_filter": true,
            "equal_height": false
          };
        }else{
          var filter_attr = "'+filter_attr+'";
          wpexAnimsition.parent_block =  wpexAnimsition.parent_block + ", [data-subpart-id=\"'+subpart.id.to_s+'\"]";
          wpexAnimsition.container_block =  wpexAnimsition.container_block + ", [data-subpart-id=\"'+subpart.id.to_s+'\"] [data-list=\"custom_announcements\"]:not(tbody)";
          if( wpexAnimsition.filter_attr.indexOf(filter_attr) == -1 ){
            wpexAnimsition.filter_attr += ("," + filter_attr);
          }
        }
        var wpexLocalize = {
          "lightboxType": "iLightbox", 
          "iLightbox": { "auto": false, "skin": "minimal", "path": "horizontal", 
                "infinite": false, "maxScale": 1, "minScale": 0, "width": 1400, "height": "",
                "slideshow": { "pauseTime": 3000, "startPaused": true }, 
                "effects": { "reposition": true, "repositionSpeed": 200, "switchSpeed": 300, 
                  "loadedFadeSpeed": 50, "fadeSpeed": 500 
                }, 
                "show": { "title": true, "speed": 200 }, 
                "hide": { "speed": 200 }, 
                "overlay": { "blur": true, "opacity": "0.9" },
                "slideShow": "Slideshow", "next": "Next", "previous": "Previous" , 
                "thumbnails": { "maxWidth": 120, "maxHeight": 80 } 
            } 
          };
        $(document).ready(function(){
          var first_filter_tab = $("[data-subpart-id=\"'+subpart.id.to_s+'\"] .filter_tab").eq(0);
          var read_more_url = first_filter_tab.data("read_more");
            if(read_more_url.length != 0){
              $("[data-subpart-id=\"'+subpart.id.to_s+'\"] .w-annc__more").attr("href",read_more_url);
              $("[data-subpart-id=\"'+subpart.id.to_s+'\"] .w-annc__more").text(first_filter_tab.data("read_more_text"));
            }
          $("[data-subpart-id=\"'+subpart.id.to_s+'\"] .filter_tab").click(function(){
            var read_more_url = $(this).data("read_more");
            if(read_more_url.length != 0){
              $("[data-subpart-id=\"'+subpart.id.to_s+'\"] .w-annc__more").attr("href",read_more_url);
              $("[data-subpart-id=\"'+subpart.id.to_s+'\"] .w-annc__more").text($(this).data("read_more_text"));
            }
          })
        })
      </script>
      <script src="/assets/custom_bulletin/wpex.min.js"></script>
      <style>
      [data-list="custom_announcements"] {
        position: relative;
      }
      </style>
      '
    else
      read_more_text = I18n.t("custom_announcement.more")
      if cats.count == 1 && cats[0] != "all"
        begin
          read_more_text = I18n.t("custom_announcement.more_") + ((all_tags.count == 1 && all_tags[0] != 'all') ? tags_translations[tags[0]] : cats_translations[cats[0]])
        rescue 
          nil
        end
      end
      extra_html = "
        <script>
          $(document).ready(function(){
            $(\"[data-subpart-id=\\\"#{subpart.id}\\\"] .w-annc__more\").text(\"#{read_more_text}\");
          })
        </script>
      "
    end
    if (@read_more_option != 0 rescue false)
      extra_html += "
        <script>

          $(document).ready(function(){
            var read_more_position = #{@read_more_option};
            var read_more_block = $(\"[data-subpart-id=\\\"#{subpart.id}\\\"] .w-annc__more\");
            if(read_more_position == 1 || read_more_position == 2){
              read_more_block.addClass(\"pull-left\");
            }else{
              read_more_block.addClass(\"pull-right\");
            }
            if(read_more_position == 1 || read_more_position == 3){
              var first_element = $(\"[data-subpart-id=\\\"#{subpart.id}\\\"] > *:eq(0)\");
              var div_clearfix = $('<div class=\"clearfix\"></div>')
              if(first_element.height() == 0){
                read_more_block.appendTo(div_clearfix);
              }else{
                div_clearfix = read_more_block;
              }
              first_element.before(div_clearfix);
            }else{
              var div_clearfix = $('<div class=\"clearfix\"></div>');
              read_more_block.appendTo(div_clearfix);
              $(\"[data-subpart-id=\\\"#{subpart.id}\\\"] > *:eq(-1)\").after(div_clearfix);
            }
          })
        </script>
      "
    end
    extra_after_html = ""
    if @all_setting_option == 0 && @tab_option == 1
     extra_after_html = "
      <script>
        $(\"[data-subpart-id=\\\"#{subpart.id}\\\"] [data-list] [data-category]\").css(\"display\",\"none\");
        $(\"[data-subpart-id=\\\"#{subpart.id}\\\"] [data-list] [data-category]:lt(#{max_all_count})\").css(\"display\",\"\");
      </script>
      "
    end
    if @tab_option == 0
      read_more_url = "/#{I18n.locale.to_s + page.get_url}" rescue ""
      read_more_url = read_more_url + "?" + {"category"=>all_cats,"tags"=>all_tags}.to_param if read_more_url != ""
      extra_after_html += "
      <script>
        $(\"[data-subpart-id=\\\"#{subpart.id}\\\"] .w-annc__more\").attr(\"href\",\"#{read_more_url}\");
      </script>
      "
    end
    {
      "custom_announcements" => custom_anns,
      "extras" => {
        "more_url"=>OrbitHelper.widget_more_url,
        "main_picture" => mp,
        "main_picture_description" => mpd,
        "title-head" => t('custom_announcement.table.title'),
        "date-head" => t('custom_announcement.table.date'),
        "author-head" => t('custom_announcement.table.author'),
        "status-head" => t('custom_announcement.table.status'),
        "subtitle-head" => t('custom_announcement.table.sub_title'),
        "category-head" => t('custom_announcement.table.category'),
        "link-head" => t('custom_announcement.table.link'),
        "file-head" => t('custom_announcement.table.file'),
        "read_more" => read_more_url,
        "read_more_text" => "read more",
        "extra_brefore_html" => extra_html,
        "extra_after_html" => extra_after_html
      }
    }
  end
  def get_tabs_option
    subpart = OrbitHelper.get_current_widget
    tab_options = ["not_enable_tabs","enable_tabs_with_categories_include_all","enable_tabs_with_categories"]
    read_more_options = ['default','upper_left','lower_left','upper_right','lower_right']
    all_setting_options = ['the_same_as_data_count','display_all_in_other_tabs']
    @tab_option = 0
    @read_more_option = 0
    @all_setting_option = 0
    if subpart.methods.include? 'select_options'.to_sym
      ModuleApp.all.select{|tmp| tmp.key.to_s=='custom_announcement'}.each do |modile_app|
        @show_options = modile_app.show_options rescue nil
      end
      subpart.select_options.each do |select_option|
        if !(@show_options.nil?) && select_option.field_name == @show_options.keys[1].to_s
          value = YAML.load(select_option.value)
          tmp = value[:en]
          I18n.with_locale(:en) do
            tab_options.each_with_index do |option,i|
              if tmp == t("custom_announcement.#{option}")
                @tab_option = i
                break
              end
            end
          end
        end
        if !(@show_options.nil?) && select_option.field_name == @show_options.keys[2].to_s
          value = YAML.load(select_option.value)
          tmp = value[:en]
          I18n.with_locale(:en) do
            read_more_options.each_with_index do |option,i|
              if tmp == t("custom_announcement.#{option}")
                @read_more_option = i
                break
              end
            end
          end
        end
        if !(@show_options.nil?) && select_option.field_name == @show_options.keys[3].to_s
          value = YAML.load(select_option.value)
          tmp = value[:en]
          I18n.with_locale(:en) do
            all_setting_options.each_with_index do |option,i|
              if tmp == t("custom_announcement.#{option}")
                @all_setting_option = i
                break
              end
            end
          end
        end
      end
    end
  end
  def get_anncs_for_pack_data(cats,tags,set_tags=nil,is_random = false)
    subpart = OrbitHelper.get_current_widget
    custom_data_field = subpart.custom_data_field
    widget_data_count = OrbitHelper.widget_data_count
    custom_anns_cache = CustomAnnsCache.where(parent_id: subpart.id.to_s + cats.to_s + tags.to_s + custom_data_field.to_s + widget_data_count.to_s,locale: I18n.locale.to_s)
    set_image_version_for_widget()
    devide_flag = (!(defined? SiteFeed).nil?)
    if custom_anns_cache.count != 1 || is_random
      CustomBulletin.remove_expired_status
      uid = OrbitHelper.params[:uid] rescue ""
      sorted_custom_anns = CustomBulletin.where(:title.nin => ["",nil],:is_preview.in=>[false,nil], :uid.ne => uid)
                      .can_display_and_sorted.is_approved
                        .filter_by_widget_categories(cats,false).filter_by_tags(tags)
      if custom_data_field
        if (custom_data_field[:bind_module_app] rescue false)
          sorted_custom_anns = sorted_custom_anns.where(:custom_module=>custom_data_field[:bind_module_app])
        end
        if (custom_data_field[:bind_uid] rescue false)
          sorted_custom_anns = sorted_custom_anns.where(:bind_uid=>custom_data_field[:bind_uid])
        end
      end
      if !is_random
        sorted_custom_anns = sorted_custom_anns.limit(widget_data_count)
        if custom_anns_cache.count > 1
          custom_anns_cache.destroy
        end
        if devide_flag
          now_custom_anns = sorted_custom_anns.to_a
          top_custom_anns = now_custom_anns.select{|v| v.is_top}.map{|v| data_to_human_type(v,set_tags)}
          not_top_custom_anns = now_custom_anns.select{|v| !v.is_top}.map{|v| data_to_human_type(v,set_tags)}
          CustomAnnsCache.create(parent_id: subpart.id.to_s + cats.to_s + tags.to_s + custom_data_field.to_s + widget_data_count.to_s,locale: I18n.locale.to_s,filter_result: {top: top_custom_anns,not_top: not_top_custom_anns})
        else
          custom_anns = sorted_custom_anns.map{|v| data_to_human_type(v,set_tags)}
          CustomAnnsCache.create(parent_id: subpart.id.to_s + cats.to_s + tags.to_s + custom_data_field.to_s + widget_data_count.to_s,locale: I18n.locale.to_s,filter_result: custom_anns)
        end
      else
        if devide_flag
          custom_anns = sorted_custom_anns.sample(widget_data_count)
          top_custom_anns = custom_anns.select{|v| v.is_top}.map{|v| data_to_human_type(v,set_tags)}
          not_top_custom_anns = custom_anns.select{|v| !v.is_top}.map{|v| data_to_human_type(v,set_tags)}
        else
          custom_anns = sorted_custom_anns.sample(widget_data_count).map{|v| data_to_human_type(v,set_tags)}
        end
      end
    elsif devide_flag
      now_custom_anns = custom_anns_cache.first.filter_result
      top_custom_anns = now_custom_anns[:top]
      not_top_custom_anns = now_custom_anns[:not_top]
    else
      custom_anns = custom_anns_cache.first.filter_result
    end
    if devide_flag
      rest_count = widget_data_count - top_custom_anns.count
      if rest_count <= 0
        custom_anns = top_custom_anns
      else
        feeds_custom_anns = get_feed_custom_announcements("widget")
        top_custom_anns = top_custom_anns + feeds_custom_anns.select{|v| v['is_top']}
        top_custom_anns = top_custom_anns.sort{|v1,v2| v2["postdate"]<=>v1["postdate"]}
        rest_all_custom_anns = feeds_custom_anns.select{|v| v['is_top'] != true} + not_top_custom_anns.take(rest_count)
        rest_custom_anns = rest_all_custom_anns.sort{|v1,v2| v2["postdate"]<=>v1["postdate"]}.take(rest_count)
        custom_anns = (top_custom_anns + rest_custom_anns).take(widget_data_count)
      end
    end
    custom_anns.each{|a| a["postdate"] = a["postdate"].in_time_zone(Time.zone.utc_offset / 3600).strftime('%Y-%m-%d %H:%M') rescue nil }
    custom_anns
  end
  def get_file
    @url = request.path
    begin
      file = CustomBulletinFile.find(params[:id])
      @url = file.file.url
      if file.can_access?(OrbitHelper.current_user)
        @path = file.file.path rescue ""
        @filename = @path.split("/").last
        @ext = @path.split("/").last.to_s.split(".").last
        if @ext == "png" || @ext == "jpg" || @ext == "bmp" || @ext == "pdf"
          render "archives/download_file.html",:layout=>false
        else
          send_file(@path)
        end
      else
        render :file => "#{Rails.root}/app/views/errors/403.html", :layout => false, :status => :not_found, :content_type => 'text/html'
      end
    rescue
      render :file => "#{Rails.root}/app/views/errors/404.html", :layout => false, :status => :not_found, :content_type => 'text/html'
    end
  end
  def show_local_custom_announcement(uid, is_preview)
    locale = OrbitHelper.get_site_locale.to_s
    if is_preview
      custom_announcement = CustomBulletin.where(:uid => uid).first
    else
      custom_announcement = CustomBulletin.can_display_and_sorted.where(:uid => uid).first
    end
    @custom_bulletin = custom_announcement
    custom_announcement = CustomBulletin.where(:uid => uid).first if custom_announcement.nil?
    url_to_edit = OrbitHelper.user_can_edit?(custom_announcement) ? "/admin/custom_announcements/#{custom_announcement.id.to_s}/edit" : ""

    access_level = OrbitHelper.user_access_level?

    if !custom_announcement.approved && (access_level != "manager" && access_level != "admin")
      if CustomAnnouncementSetting.is_pro?
        if !(access_level == "sub_manager" && CustomAnnouncementSetting.first.approvers.include?(OrbitHelper.current_user.id.to_s))
          return {}
        end
      elsif access_level != "sub_manager"
        return {}
      end
    end

    return {} if (custom_announcement.category.disable rescue false)

    tags = custom_announcement.tags.map{|tag|  {
      "tag" => tag.name ,
      "url" => OrbitHelper.page_for_tag(tag)
    } } rescue []
    files = custom_announcement.custom_bulletin_files.map do |file|  
              { "file_url" =>  "/xhr/custom_announcements/file/#{file.id}/#{file['file']}" + "\" title=\"#{file.file_title}", 
                "file_title" => (file.title.blank? ? URI.unescape(File.basename(file.file.path)) : file.title rescue '') } rescue nil if file.enabled_for?(locale)
            end rescue []
    files.delete(nil)
    files.each do |file|
      if file["file_url"] =="" || file["file_url"] == nil
        files.delete(file)
      end
    end
    links = custom_announcement.custom_bulletin_links.map{|link|  { "link_url" => link.url, "link_title" => (link.title.blank? ? link.url : link.title) } } rescue []
    update_user = custom_announcement.update_user.member_profile.name rescue ""
    desc = custom_announcement.image_description
    desc = (desc.nil? || desc == "" ? "custom_announcement image" : desc)

    request = OrbitHelper.request
    meta_desc = custom_announcement.subtitle.nil? || custom_announcement.subtitle == ""  ? custom_announcement.text[0..200] : custom_announcement.subtitle
    OrbitHelper.render_meta_tags([{"property" => "og:title", "content" => custom_announcement.title},{"property" => "og:site_name", "content" => Site.first.title},{"property" => "og:url", "content" => request.original_url.split("?").first},{"property" => "og:description", "content" => meta_desc},{"property" => "og:image", "content" => "#{request.base_url}#{custom_announcement.image.url}"},{"property" => "og:type", "content" => "Article"}])

    subtitle_ann = nil
    img_src = nil
    img_description = nil
    subtitle_ann = custom_announcement.subtitle if custom_announcement.display_subtitle?
    img_src = (custom_announcement.image.thumb.url || "/assets/custom_announcement-default.jpg") if custom_announcement.display_img?
    img_description = custom_announcement.image_description if (custom_announcement.image_description.present?) && (custom_announcement.display_img?)
    show_comment_flag = custom_announcement.open_comment_for_user(OrbitHelper.current_user)
    custom_bulletin_carousel_images = custom_announcement.custom_bulletin_carousel_images.map{|image| {"src"=>image.file.url,"description"=>image.description.to_s,"description_text"=>image.description_text }}
    resume_btn_title = (I18n.locale.to_s =="zh_tw") ? "繼續播放" : "resume"
    pause_btn_title = (I18n.locale.to_s =="zh_tw") ? "暫停播放" : "pause"
    prev_btn_title = (I18n.locale.to_s =="zh_tw") ? "上一張" : "prev"
    next_btn_title = (I18n.locale.to_s =="zh_tw") ? "下一張" : "next"
    {
      "tags" => tags,
      "custom_bulletin_files" => files,
      "custom_bulletin_links" => links,
      "custom_bulletin_carousel_images" => custom_bulletin_carousel_images,
      "data" => {
        "title" => custom_announcement.title,
        "subtitle_ann" => subtitle_ann,
        "update_user" => update_user,
        "updated_at" => (custom_announcement.postdate.in_time_zone(Time.zone.utc_offset / 3600).strftime('%Y-%m-%d %H:%M') rescue ""),
        "body" =>custom_announcement.text,
        "image" => custom_announcement.image.url,
        "img_src" => img_src,
        "img_description" => img_description,
        "hide_class" => custom_announcement.display_img? ? custom_announcement.image_display_class : ' hide',
        "alt_title" => desc,
        "resume_btn_title" => resume_btn_title,
        "pause_btn_title" => pause_btn_title,
        "prev_btn_title" => prev_btn_title,
        "next_btn_title" => next_btn_title,
        "carousel_display_style" => (custom_bulletin_carousel_images.count == 0 ? 'display: none' : 'width: 50%;margin: auto;'),
        "carousel_count" => custom_bulletin_carousel_images.count
      },
      "comments" => custom_announcement.comments,
      "show_comment_flag" => show_comment_flag,
      "impressionist" => (custom_announcement.is_preview ? nil : custom_announcement),
      "url_to_edit"=>url_to_edit
    }
  end

  def show_feed_custom_announcement(uid)
    custom_announcement = OrbitHelper.get_from_feed(uid)
    locale = OrbitHelper.get_site_locale.to_s
    url_to_edit = "#"
    return {} if custom_announcement.blank?
    tags = []

    custom_announcement["tags"].each{|tag|
      t = Tag.where(:name => tag["name_translations"][locale]).first rescue nil
      if t.nil?
        I18n.locale = (locale == "en" ? :zh_tw : :en)
        t = Tag.where(:name => tag["name_translations"][locale]).first rescue nil
        I18n.locale = locale.to_sym
      end
      tags << {
        "tag" => tag["name_translations"][locale],
        "url" => (t.nil? ?  "#" : OrbitHelper.page_for_tag(t))
      }
    }

    files = custom_announcement["custom_bulletin_files"].map{|file|  { "file_url" =>  file["url"], "file_title" => (file["title_translations"][locale] == "" ? URI.unescape(File.basename(file["url"])) : file["title_translations"][locale] rescue '') } } rescue []

    files.each do |file|
      if file["file_url"] =="" || file["file_url"] == nil
        files.delete(file)
      end
    end
    links = custom_announcement["custom_bulletin_links"].map{|link|  { "link_url" => link["url"], "link_title" => (link["title_translations"][locale] == "" ? link["url"] : link["title_translations"][locale]) } } rescue []

    update_user = custom_announcement["author"]
    desc = custom_announcement["image_description_translations"][locale] rescue ""
    desc = (desc.nil? || desc == "" ? "custom_announcement image" : desc)
    img_description = nil
    img_description = custom_announcement["image_description_translations"][I18n.locale] if custom_announcement['display_img']
    img_src = nil
    img_src = (custom_announcement['image']['thumb'] || "/assets/custom_announcement-default.jpg") if custom_announcement['display_img']
    subtitle_ann = custom_announcement['subtitle_ann']
    request = OrbitHelper.request
    if custom_announcement["subtitle_translations"].present?
      meta_desc = custom_announcement["subtitle_translations"][locale] != "" ? custom_announcement["subtitle_translations"][locale] : custom_announcement["text_translations"][locale][0..200] rescue ""
    else
      meta_desc = ""
    end

    OrbitHelper.render_meta_tags([{"property" => "og:title", "content" => custom_announcement["title_translations"][locale]},{"property" => "og:site_name", "content" => Site.first.title},{"property" => "og:url", "content" => request.original_url.split("?").first},{"property" => "og:description", "content" => meta_desc},{"property" => "og:image", "content" => custom_announcement["image"]["original"]},{"property" => "og:type", "content" => "Article"}])

    datetime = DateTime.parse(custom_announcement["postdate"])

    custom_bulletin_carousel_images = Array(custom_announcement["custom_bulletin_carousel_images"])
    resume_btn_title = (I18n.locale.to_s =="zh_tw") ? "繼續播放" : "resume"
    pause_btn_title = (I18n.locale.to_s =="zh_tw") ? "暫停播放" : "pause"
    prev_btn_title = (I18n.locale.to_s =="zh_tw") ? "上一張" : "prev"
    next_btn_title = (I18n.locale.to_s =="zh_tw") ? "下一張" : "next"

    {
      "tags" => tags,
      "custom_bulletin_files" => files,
      "custom_bulletin_links" => links,
      "custom_bulletin_carousel_images" => custom_bulletin_carousel_images,
      "data" => {
        "title" => custom_announcement["title_translations"][locale],
        "subtitle_ann" => subtitle_ann,
        "update_user" => update_user,
        "updated_at" => (datetime.in_time_zone(Time.zone.utc_offset / 3600).strftime('%Y-%m-%d %H:%M') rescue ""),
        "body" => custom_announcement["text_translations"][locale],
        "image" => custom_announcement["image"]["original"],
        "img_src" => img_src,
        "img_description" => img_description,
        "hide_class" => custom_announcement["display_img"]  ? '' : ' hide',
        "alt_title" => desc,
        "resume_btn_title" => resume_btn_title,
        "pause_btn_title" => pause_btn_title,
        "prev_btn_title" => prev_btn_title,
        "next_btn_title" => next_btn_title,
        "carousel_display_style" => (custom_bulletin_carousel_images.count == 0 ? 'display: none' : 'width: 50%;margin: auto;'),
        "carousel_count" => custom_bulletin_carousel_images.count
      },
      "comments" => [],
      "show_comment_flag" => false,
      "impressionist" => nil,
      "url_to_edit" => url_to_edit
    }
  end

  def show
    params = OrbitHelper.params
    uid = params[:uid]
    if OrbitHelper.is_object_from_feed?(uid)
      show_feed_custom_announcement(uid)
    else
      show_local_custom_announcement(uid, (params["preview"] == "true" ? true : false))
    end
  end
  def show_widget
    @type = "show_widget"
    @show_page = params[:show_page]
    if params[:tags].nil?
      @tags = ['all']
    else
      @tags = params[:tags]
    end
    if params[:categories].nil?
      @categories = ['all']
    else
      @categories = params[:categories]
    end
    OrbitHelper.set_site_locale(I18n.locale)
    OrbitHelper.set_current_widget_module("custom_announcement")
    OrbitHelper.set_params(params,current_user)
    CustomBulletin.remove_expired_status
    OrbitHelper.set_page_number(params[:page_no].to_i)
    OrbitHelper.set_page_data_count((params[:data_count].blank? ? 10 : params[:data_count].to_i))
    sorted,total_pages = get_sorted_annc
    custom_anns = sorted.collect do |a|
      if a["source-site"].blank?
        statuses = a.statuses_with_classname.collect do |status|
          {
            "status" => status["name"],
            "status-class" => "status-#{status['classname']}"
          }
        end
        locale = I18n.locale.to_s
        files = a.custom_bulletin_files.map{|file|  { "file_url" =>  file.file.url + "\" title=\"#{file.file_title}", "file_title" => (file.title.blank? ? File.basename(file.file.path) : file.title rescue '') } if file.enabled_for?(locale) } rescue []
        files.delete(nil)
        links = a.custom_bulletin_links.map{|link|  { "link_url" => link.url, "link_title" => (link.title.blank? ? link.url : link.title) } } rescue []
        author = User.find(a.create_user_id).member_profile.name rescue ""
        desc = a.image_description
        desc = (desc.blank? ? "custom_announcement image" : desc)
        link_to_show = (a.is_external_link ? a.external_link :  OrbitHelper.url_to_show(a.to_param)) rescue ""
        target = a.is_external_link ? "_blank" : "_self"
        doc = Nokogiri::HTML(a.title)
        title = doc.text.empty? ? 'no content' : doc.text
        {
          "department" => author,
          "custom_bulletin_links" => links,
          "custom_bulletin_files" => files,
          "title" => a.title,
          "source-site" => "",
          "source-site-title" => "",
          "source-site-link" => "",
          "subtitle" => a.subtitle,
          "statuses" => statuses,
          "category" => a.category.title,
          "postdate" => a.postdate,
          "author" => author,
          "is_top" => (a.is_top? ? 1 : 0),
          "link_to_show" => link_to_show+"\" title=\"#{title}\"",
          "target" => target,
          "img_src" => a.image.thumb.url || "/assets/custom_announcement-default.jpg",
          "img_description" => desc,
          "more" => t(:more_plus),
          "view_count" => a.view_count
        }
      else
        a
      end
    end
    #If no data , hide title&table
    if sorted.count == 0
      display = "hide"
    end
    # custom_anns = custom_anns.concat(feeds_custom_anns)
    # total_pages = custom_announcements.total_pages


    @data = {
      "custom_announcements" => custom_anns,
      "extras" => {
        "widget-title" =>t('custom_announcement.custom_announcement'),
        "title-head" => t('custom_announcement.table.title'),
        "date-head" => t('custom_announcement.table.date'),
        "status-head" => t('custom_announcement.table.status'),
        "author-head" => t('custom_announcement.table.author'),
        "subtitle-head" => t('custom_announcement.table.sub_title'),
        "category-head" => t('custom_announcement.table.category'),
        "link-head" => t('custom_announcement.table.link'),
        "file-head" => t('custom_announcement.table.file'),
        "view-count-head" => t('custom_announcement.table.view_count'),
        "display" => display,
        "department-head" => t('custom_announcement.table.department')
      },
      "total_pages" => total_pages
    }
    render :layout => false
  end

end
