# encoding: utf-8
require 'rubyXL'
class Admin::CustomAnnouncementsController < OrbitAdminController
  include Admin::CustomAnnouncementsHelper
  before_action ->(module_app = @app_title) { set_variables module_app }
  before_action :set_custom_bulletin, only: [:edit, :destroy, :comment]
  before_action :load_access_level, :load_settings
  before_action :set_module_pages, only: [:edit,:new]
  def set_module_pages
    @module_pages = Page.where(:module => 'custom_announcement').collect{|p| [p.name,p.id] }
  end
  def initialize
    super
    @app_title = "custom_announcement"
  end
  def comment_hidden
    b = CustomBulletinComment.find(params[:id]) rescue nil
    if !b.nil?
      b.is_hidden = !b.is_hidden
      b.save
      @table_feed_fields = ["custom_announcement.time", "custom_announcement.comment", "custom_announcement.account","ip","is_hidden"]
      @comments = b.custom_bulletin.custom_bulletin_comments.reverse rescue []
      render partial: 'comment'
    end
  end
  def comment
    @table_feed_fields = ["custom_announcement.time", "custom_announcement.comment", "custom_announcement.account","ip","is_hidden"]
    @comments = @custom_bulletin.custom_bulletin_comments.reverse rescue []
  end
  def index
    @custom_bulletin_configs = CustomBulletinConfig.all
    CustomBulletin.remove_expired_status
    @tags = @module_app.tags
    @table_fields = [:status, :category, :title, :start_date, :end_date, "custom_announcement.comment", :last_modified]
    @current_user = current_user
    if CustomAnnouncementSetting.first.is_display_edit_only && !current_user.is_admin? && !current_user.is_manager?(@module_app)
      current_user_is_sub_manager = !current_user.is_manager?(@module_app) && (current_user.is_sub_manager?(@module_app) || current_user.is_sub_manager_with_role?(@module_app)) rescue false
      if current_user_is_sub_manager
        @categories = current_user.approved_categories.select{|c| c.module_app_id == @module_app.id} rescue []
        @filter_fields = filter_fields(@categories, @tags)
        @custom_bulletins = CustomBulletin.where(:create_user_id=>current_user.id,:is_preview.in=>[false,nil])
                                        .order_by(sort)
                                        .with_categories(filters("category"))
                                        .with_tags(filters("tag"))
                                        .with_status(filters("status"))
      else
        @custom_bulletins = CustomBulletin.where(:uid=>nil)
        @categories = @module_app.categories.enabled
        @filter_fields = filter_fields(@categories, @tags)
      end
    else
      @categories = @module_app.categories.enabled
      @filter_fields = filter_fields(@categories, @tags)
      @custom_bulletins = CustomBulletin.where(:is_preview.in=>[false,nil])
                                        .order_by(sort)
                                        .with_categories(filters("category"))
                                        .with_tags(filters("tag"))
                                        .with_status(filters("status"))
    end
    if params[:custom_module].present?
      @custom_bulletins = @custom_bulletins.where(:custom_module=>params[:custom_module])
    end
    if params[:bind_uid].present?
      @custom_bulletins = @custom_bulletins.where(:bind_uid=>params[:bind_uid])
    end
    @custom_bulletins = search_data(@custom_bulletins,[:title]).page(params[:page]).per(10)
    
    if request.xhr?
      render :partial => "index"
    elsif params[:custom_module].blank? || params[:bind_uid].blank?
      render "display_enable_modules"
    end
  end

  def feed
    @table_feed_fields = ["custom_announcement.feed_name", :tags, "custom_announcement.rssfeed", "custom_announcement.jsonfeed"]
    @feeds = CustomBulletinFeed.all.asc(:created_at)
    
  end
  def generate_iframe_url
    iframe_params = params.require(:iframe).permit!
    uids = iframe_params['member_ids'].to_a.map{|m_id| MemberProfile.find(m_id).uid rescue nil}.select{|uid| !uid.nil?}
    url_params = iframe_params.except(:member_ids)
    url_params['uids'] = uids if uids != []
    render :text => '/xhr/panel/custom_announcement/widget/sync_data?'+url_params.to_param
  end
  def settings
    @setting = @custom_announcement_setting
    roles = Role.all
    @sorted_members = roles.inject({}) do |members,role|
      members_for_role =  role.member_profiles.select{|m| (m.user.nil? ? false : m.user.approved)}
      members[role] = members_for_role
      members
    end
    @sorted_members['no_role'] = MemberProfile.any_in(:role_ids=>[nil,[]]).select{|m| (m.user.nil? ? false : m.user.approved)}
    @unapproved_members = User.where(:approved => false).map{|u| u.member_profile}
  end

  def import
  end

  def excel_format
    respond_to do |format|
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="custom_announcement_import_format.xlsx"'
      }
    end
  end

  def export_excel
    @custom_announcements = CustomBulletin.all.desc(:created_at)
    respond_to do |format|
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="custom_announcement_export.xlsx"'
      }
    end
  end

  def import_from_xml
    download_tmp_xml params["import_xml"]
    import_from_tmp_xml File.read(File.join(Rails.root, "tmp", "ann_cc_ntu.xml"))
    redirect_to admin_custom_announcements_path
  end

  def import
  end


  def import_from_wp
    import_from_wordpress params["import_xml"].tempfile
    redirect_to admin_custom_announcements_path
  end 

  def importcustom_anns
    workbook = RubyXL::Parser.parse(params["import_file"].tempfile)
    categories = @module_app.categories.asc(:created_at).to_a
    tags = @module_app.tags.asc(:created_at).to_a
    sheet = workbook[0]
    if sheet.count <= 503
      sheet.each_with_index do |row, i|
        next if i < 3
        v = row.cells.first.value rescue nil
        next if v.blank?
        import_this_custom_announcement(row, categories, tags)
      end
      redirect_to admin_custom_announcements_path
    else
      redirect_to admin_custom_announcements_path(:error => "1")
    end
  end

  def createsettings
    setting = CustomAnnouncementSetting.new(settings_params)
    setting.save
    redirect_to admin_custom_announcement_settings_path
  end
  
  def updatesettings
    setting = @custom_announcement_setting
    ids = params['custom_announcement_setting']['custom_anns_status_settings'].to_a.collect do |i,v|
      v['_id']
    end.compact
    CustomAnnsStatusSetting.where(:id.nin=>ids).destroy
    setting.update_attributes(settings_params)
    setting.save
    redirect_to admin_custom_announcement_settings_path
  end

  def feedform
    if params[:type] == "new"
      @custom_announcement_feed = CustomBulletinFeed.new
      render :partial => "feed_form"
    else params[:type] == "edit"
      @custom_announcement_feed = CustomBulletinFeed.find(params[:id])
      render :partial => "edit_feed_form"
    end
  end

  def createfeed
    custom_announcement_feed = CustomBulletinFeed.new(feed_params)
    custom_announcement_feed.save
    create_feed_cache(nil,custom_announcement_feed)
    feeds = CustomBulletinFeed.all.asc(:created_at)
    render :partial => "feed", :collection => feeds
  end

  def updatefeed
    ann_feed  = CustomBulletinFeed.find(params[:id])
    ann_feed.update_attributes(feed_params)
    ann_feed.save
    create_feed_cache(nil,ann_feed)
    feeds = CustomBulletinFeed.all.asc(:created_at)
    render :partial => "feed", :collection => feeds
  end

  def deletefeed
    ann_feed  = CustomBulletinFeed.find(params[:id])
    ann_feed.destroy
    feeds = CustomBulletinFeed.all.asc(:created_at)
    render :partial => "feed", :collection => feeds
  end

  def new
    @tags = @module_app.tags
    @statuses = []
    @custom_bulletin = CustomBulletin.new
    @custom_bulletin.email_sentdate = Time.now
    @reach_limit = @custom_bulletin.check_status_limit(current_user,true)
    if defined? Calendar
      categories = user_authenticated_categories rescue ['all']
      if categories.first == "all"
        @calendar_categories = CalendarType.all
      else
        @calendar_categories = CalendarType.where(:category_id.in => categories) rescue []
      end
    end
  end

  def create
    bps = custom_bulletin_params
    custom_bulletin = CustomBulletin.new(bps)
    if !bps['custom_bulletin_links_attributes'].nil?
      bps['custom_bulletin_links_attributes'].each do |idx,link|
        bps['custom_bulletin_links_attributes'].delete(idx.to_s) if link['url'].blank?
      end
    end
    if((!CustomAnnouncementSetting.first.only_manager_can_edit_status) || (CustomAnnouncementSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
      if bps[:is_top] == "1" && !CustomAnnouncementSetting.check_limit_for_user(custom_bulletin.create_user_id, custom_bulletin.id)
        bps[:is_top] = "0"
        bps[:top_end_date] = nil
      end
    else
      bps[:is_top] = false
      bps[:is_hot] = false
      bps[:is_hidden] = false
    end

    if !defined?(Calendar).nil?
      bps = update_calendar(bps,custom_bulletin)
    end
    custom_bulletin.create_user_id = current_user.id
    custom_bulletin.update_user_id = current_user.id
    if CustomAnnouncementSetting.is_pro?
      if user_can_approve?
        custom_bulletin.approved = true
      else
        send_notification_mail_to_managers(custom_bulletin,"approval",I18n.locale)
      end
    else
      custom_bulletin.approved = true
    end
    
    custom_bulletin.save
    build_email(custom_bulletin,I18n.locale)
    create_feed_cache(custom_bulletin)
    if bps[:custom_module].present?
      redirect_to admin_custom_announcements_path + "/#{bps[:custom_module]}#{bps[:bind_uid].present? ? ('-'+bps[:bind_uid]) : ''}"
    else
      redirect_to admin_custom_announcements_path
    end
  end

  def approve_custom_bulletin
    id = params[:id]
    custom_bulletin = CustomBulletin.find(id)
    if params["approved"] == "true"
      custom_bulletin.approved = true
      custom_bulletin.rejected = false
      custom_bulletin.reapproval = false
    else
      custom_bulletin.rejected = true
      custom_bulletin.reapproval = false
      custom_bulletin.rejection_reason = params["reason"]
      send_rejection_email(custom_bulletin,I18n.locale)
    end
    custom_bulletin.save
    create_feed_cache(custom_bulletin)
    redirect_to admin_custom_announcements_path
  end

  def edit
    if can_edit_or_delete?(@custom_bulletin)
      @reach_limit = @custom_bulletin.check_status_limit(current_user,true)
      @tags = @module_app.tags
      @categories = @module_app.categories.enabled
      if defined? Calendar
        categories = user_authenticated_categories rescue ['all']
        if categories.first == "all"
          @calendar_categories = CalendarType.all
        else
          @calendar_categories = CalendarType.where(:category_id.in => categories) rescue []
        end
      end
      @statuses = []
      @custom_bulletin.email_sentdate = Time.now if @custom_bulletin.email_sent == false
    else
      render_401
    end
  end

  def update
    uid = params[:id].split('-').last
    custom_bulletin = CustomBulletin.find_by(:uid=>uid)
    bps = custom_bulletin_params
    bps[:tags] = bps[:tags].blank? ? [] : bps[:tags]
    bps[:email_member_ids] = bps[:email_member_ids].blank? ? [] : bps[:email_member_ids]

    if !bps['custom_bulletin_links_attributes'].nil?
      bps['custom_bulletin_links_attributes'].each do |idx,link|
        bps['custom_bulletin_links_attributes'].delete(idx.to_s) if link['url'].blank?
      end
    end
    if((!CustomAnnouncementSetting.first.only_manager_can_edit_status) || (CustomAnnouncementSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
      if bps[:is_top] == "1" && !CustomAnnouncementSetting.check_limit_for_user(custom_bulletin.create_user_id, custom_bulletin.id)
        bps[:is_top] = "0"
        bps[:top_end_date] = nil
      end
    else
      bps[:is_top] = custom_bulletin.is_top
      bps[:is_hot] = custom_bulletin.is_hot
      bps[:is_hidden] = custom_bulletin.is_hidden
    end
    if !defined?(Calendar).nil?
      bps = update_calendar(bps,custom_bulletin)
    end
    custom_bulletin.update_attributes(bps)
    custom_bulletin.update_user_id = current_user.id
    if custom_bulletin.rejected
      custom_bulletin.reapproval = true
      custom_bulletin.save
      send_notification_mail_to_managers(custom_bulletin,"reapproval",I18n.locale)
    else
      custom_bulletin.save
    end
    build_email(custom_bulletin,I18n.locale)
    create_feed_cache(custom_bulletin)
    custom_module = custom_bulletin.custom_module
    now_custom_bulletin_page = CustomBulletin.where(:custom_module=>custom_module,:title.ne => "",:is_preview.in=>[false,nil])
                              .order_by(sort).map(&:id).map.with_index.select{|v,i| v==custom_bulletin.id}[0][1] rescue nil
    now_custom_bulletin_page = now_custom_bulletin_page.nil? ? 0 : ((now_custom_bulletin_page+1).to_f/10).ceil
    bind_uid = custom_bulletin.bind_uid
    if custom_module.present?
      redirect_to admin_custom_announcements_path + "/#{custom_module}#{bind_uid.present? ? ('-'+bind_uid) : ''}?page=#{now_custom_bulletin_page}"
    else
      redirect_to admin_custom_announcements_path(:page=>now_custom_bulletin_page)
    end
  end

  def destroy
    custom_module = @custom_bulletin.custom_module
    bind_uid = @custom_bulletin.bind_uid
    @custom_bulletin.destroy
    if custom_module.present?
      redirect_to admin_custom_announcements_path + "/#{custom_module}#{bind_uid.present? ? ('-'+bind_uid) : ''}"
    else
      redirect_to admin_custom_announcements_path
    end
  end

  def delete
    if params[:ids]
      CustomBulletin.any_in(:uid => params[:ids]).destroy_all
    end
    redirect_to admin_custom_announcements_path
  end

  def preview
    if params['preview_type'].eql?('edit')
      custom_bulletin_data = custom_bulletin_params
      org_custom_bulletin = CustomBulletin.find(params['custom_bulletin_id'])
      custom_bulletin = org_custom_bulletin.clone
      custom_bulletin.generate_uid
      custom_bulletin.custom_bulletin_files = []
      custom_bulletin.custom_bulletin_links = []
      if custom_bulletin_data['image'].blank?
        custom_bulletin.image = org_custom_bulletin.image
      end

      if !custom_bulletin_data['custom_bulletin_files_attributes'].blank?
        custom_bulletin_data['custom_bulletin_files_attributes'].each do |key, custom_bulletin_file|
          next if !custom_bulletin_file['_destroy'].blank?
          file = nil
          if custom_bulletin_file['id'].blank?
            file = CustomBulletinFile.new(custom_bulletin_file)
            file.custom_bulletin_id = custom_bulletin.id
            file.save
          else
            org_file = CustomBulletinFile.find(custom_bulletin_file['id'])
            file = org_file.clone
            file.custom_bulletin_id = custom_bulletin.id
            file.file = org_file.file
            custom_bulletin_file.delete('id')
            custom_bulletin_file.delete('_destroy')
            file.update_attributes(custom_bulletin_file)
          end

          file.save
          custom_bulletin.custom_bulletin_files << file
        end
      end

      if !custom_bulletin_data['custom_bulletin_links_attributes'].blank?
        custom_bulletin_data['custom_bulletin_links_attributes'].each do |key, custom_bulletin_link|
          next if !custom_bulletin_link['_destroy'].blank?

          if custom_bulletin_link['id'].blank?
            link = CustomBulletinLink.new(custom_bulletin_link)
            link.custom_bulletin_id = custom_bulletin.id
          else
            link = CustomBulletinLink.find(custom_bulletin_link['id']).clone
            link.custom_bulletin_id = custom_bulletin.id
            custom_bulletin_link.delete('id')
            custom_bulletin_link.delete('_destroy')
            link.update_attributes(custom_bulletin_link)
          end

          link.save
          custom_bulletin.custom_bulletin_links << link
        end
      end

      custom_bulletin_data.delete('custom_bulletin_files_attributes')
      custom_bulletin_data.delete('custom_bulletin_links_attributes')
      custom_bulletin.update_attributes(custom_bulletin_data)
    else
      custom_bulletin = CustomBulletin.new(custom_bulletin_params)
    end
    
    custom_bulletin.is_preview = true
    custom_bulletin.save
    create_feed_cache(custom_bulletin)
    render :text=>page_for_custom_bulletin(custom_bulletin) + "?preview=true"
  end

  def destroy_preview
    custom_bulletin = CustomBulletin.find_by(:uid=>params['uid'])
    if custom_bulletin.is_preview
      custom_bulletin.destroy
    end
    render :json=>{'destroy'=>custom_bulletin.id.to_s}
  end

  def build_email(custom_bulletin,locale)
    if custom_bulletin.email_sent and !custom_bulletin.email_addresses.blank?
      if custom_bulletin.email.nil?
        email = Email.new
        email.save
        email.deliver rescue nil
        custom_bulletin.email_id = email.id
        custom_bulletin.save
      end

      is_sent = custom_bulletin.email.is_sent
      is_sent = !params[:resend_mail].eql?("true") if !params[:resend_mail].blank?
      doc = Nokogiri::HTML(custom_bulletin.title_translations[locale])
      title = doc.text.empty? ? 'no content' : doc.text
        
      custom_bulletin.email.update_attributes(
        :create_user=>current_user,
        :mail_sentdate=>custom_bulletin.email_sentdate,
        :module_app=>@module_app,
        :mail_lang => locale,
        :mail_to=>custom_bulletin.email_addresses,
        :mail_subject=>title,
        :template=>'custom_announcements/email',
        :template_data=>{
          "host" => request.host_with_port,
          "title" => title,
          "url" => page_for_custom_bulletin(custom_bulletin)
        },
        :is_sent=>is_sent
      )
      custom_bulletin.email.deliver
    else
      custom_bulletin.email.destroy if !custom_bulletin.email.nil?
    end
  end

  private

  def load_settings
    @custom_announcement_setting = CustomAnnouncementSetting.first rescue nil
    if @custom_announcement_setting.nil?
      @custom_announcement_setting = CustomAnnouncementSetting.create
    end
  end

  def set_custom_bulletin
    @custom_bulletin = CustomBulletin.find(params[:id])
  end
  def custom_bulletin_config_params
    params.require(:custom_bulletin_config).permit!
  end
  def custom_bulletin_params
    params[:custom_bulletin][:email_sent] = params[:custom_bulletin][:email_sent].nil? ? 0 : params[:custom_bulletin][:email_sent]
    params.require(:custom_bulletin).permit!
  end

  def feed_params
    params.require(:custom_bulletin_feed).permit!
  end

  def settings_params
    params.require(:custom_announcement_setting).permit!
  end
  def update_calendar(bps,custom_bulletin)
    if bps[:add_to_calendar] == '0' && !bps[:event_id].blank?
      Event.find(bps[:event_id]).destroy rescue nil
      bps[:event_id] = nil
    elsif bps[:add_to_calendar] == '1'
      event = Event.find(bps[:event_id]) rescue Event.new(create_user_id: current_user.id)
      e_start = bps[:calendar_start_date].blank? ? bps[:postdate] : bps[:calendar_start_date]
      e_start = Time.now.to_datetime if e_start.blank?
      e_end = bps[:calendar_end_date].blank? ? bps[:deadline] : bps[:calendar_end_date]
      #e_end = Time.now.to_datetime + 1.year if e_end.blank?
      event.update_attributes(model_class: 'CustomBulletin',
                              module_key: 'custom_announcement',
                              model_cat: bps[:category_id],
                              model_tags: bps[:tags],
                              model_page_id: bps[:page_id],
                              model_id: custom_bulletin.id,start: e_start,
                              end: e_end,update_user_id: current_user.id,
                              all_day: bps[:calendar_all_day],
                              calendar_type_id: bps[:calendar_type_id],
                              title_translations: bps[:title_translations],
                              note_translations: bps[:subtitle_translations])
      bps[:event_id] = event.id
    end
    bps 
  end
  def create_feed_cache(custom_bulletin=nil,custom_bulletin_feed=nil)
    if !custom_bulletin.nil?
      CustomBulletinFeed.where(:tag_ids.in => Array(custom_bulletin.tag_ids).collect{|v| v.to_s}).each do |custom_bulletin_feed|
        uid = custom_bulletin_feed.uid
        uri = URI(request.protocol + request.host_with_port + "/xhr/custom_announcements/feed/#{uid}.json")
        Thread.new do
          res_net = Net::HTTP.start(uri.host, uri.port,:use_ssl => uri.scheme == 'https',open_timeout: 60,read_timeout: 60) do |http|
            req = Net::HTTP::Get.new(uri)
            http.request(req)
          end
        end
      end
    elsif !custom_bulletin_feed.nil?
      uid = custom_bulletin_feed.uid
      uri = URI(request.protocol + request.host_with_port + "/xhr/custom_announcements/feed/#{uid}.json")
      Thread.new do
        res_net = Net::HTTP.start(uri.host, uri.port,:use_ssl => uri.scheme == 'https',open_timeout: 60,read_timeout: 60) do |http|
          req = Net::HTTP::Get.new(uri)
          http.request(req)
        end
      end
    end
  end 
end
