class CustomGalleriesController < ApplicationController

  find_tag = Tag.all.select{|value| value.name==I18n.t('custom_gallery.not_show_desc')}
  if find_tag.length==0
    module_app_id = ModuleApp.where(:key=>"custom_gallery").first[:_id]
    tags = ModuleApp.where(:key=>"custom_gallery").first.tags
    tag0 = Tag.new(is_default: false,module_app_ids: [module_app_id])
    tag1 = Tag.new(is_default: false,module_app_ids: [module_app_id])
    nowlocale = I18n.locale
    I18n.available_locales.each do |locale|
      I18n.locale = locale
      tag0.name = I18n.t('custom_gallery.show_desc')
      tag1.name = I18n.t('custom_gallery.not_show_desc')
    end
    I18n.locale = nowlocale
    tag0.save
    tag1.save
    tags << tag0
    tags << tag1
  elsif find_tag.length>1
    show_tags = Tag.all.select{|value| value.name==I18n.t('custom_gallery.show_desc')}
    show_tags.each_with_index do |show_tag,index1|
      if index1>0
        if show_tag.taggings.count==0
          show_tag.delete
        end
      end
    end
    find_tag.each_with_index do |not_show_tag,index1|
      if index1>0
        if not_show_tag.taggings.count==0
          not_show_tag.delete
        end
      end
    end
  end

  def index
    @custom_album_setting = CustomAlbumSetting.first
    params = OrbitHelper.params
    page = OrbitHelper.page rescue nil
    unless page
      page = Page.where(url:params['url']).first
    end
    custom_data_field = page.custom_data_field rescue nil
    if custom_data_field.nil?
      custom_data_field = {}
    elsif custom_data_field["bind_module_app"]
      custom_data_field["custom_module"] = custom_data_field["bind_module_app"]
      custom_data_field.delete('bind_module_app')
    end
    custom_album_tp = CustomAlbum.where(custom_data_field).filter_by_categories.filter_by_tags
    all_count = custom_album_tp.count
    page_data_count = OrbitHelper.page_data_count
    no_order_count = custom_album_tp.where(:order.in=>[-1,nil]).count
    with_order_count = all_count - no_order_count
    with_order_total_pages = (with_order_count.to_f / page_data_count).ceil
    custom_albums_with_order = custom_album_tp.asc(:order).where(:order.ne=>-1).and(:order.ne=>nil).to_a rescue []
    page_no = (params[:page_no] || 1).to_i
    if page_no < with_order_total_pages
      custom_albums_no_order = []
    elsif page_no == with_order_total_pages
      if custom_albums_with_order.count == page_data_count
        custom_albums_no_order = []
      else
        custom_albums_no_order = custom_album_tp.desc(:created_at).where(:order.in=>[-1,nil]).page(nil).per(all_count)[0...(page_data_count - custom_albums_with_order.count)]
      end
    else
      custom_albums_with_order = []
      start_index = (page_data_count - (with_order_count % page_data_count) + page_data_count*(page_no - 1 - with_order_total_pages))
      custom_albums_no_order = custom_album_tp.desc(:created_at).where(:order.in=>[-1,nil]).page(nil).per(all_count)[start_index...(start_index+page_data_count)].to_a
    end
    custom_albums = custom_albums_with_order.concat(custom_albums_no_order)
    custom_album_color_map = CustomAlbumColor.where(:custom_album_id.in=> custom_albums.map{|v| v.id}).pluck(:custom_album_id,:color,:custom_album_card_background_color,:custom_album_card_text_color).map{|v| [v[0],v[1..-1]]}.to_h
    custom_galleries = custom_albums.collect do |a|
      doc = Nokogiri::HTML(a.description.to_s)
      alt_text = doc.text.empty? ? 'custom_gallery image' : doc.text
      colors = custom_album_color_map[a.id]
      {
        "custom_album-name" => a.name,
        "custom_album-description" => a.description,
        "alt_title" => alt_text,
        "link_to_show" =>  OrbitHelper.url_to_show(a.to_param),
        "thumb-src" => a.cover_path || "/assets/custom_gallery/default.jpg",
        "custom_album_color" => iterate_data(colors[1],colors[0],@custom_album_setting.custom_album_card_background_color,'transparent'),
        "custom_album_card_text_color" => iterate_data(colors[2],@custom_album_setting.custom_album_card_text_color)
      }
    end
    {
      "custom_albums" => custom_galleries,
      "extras" => {"widget-title"=>"CustomGallery"},
      "total_pages" => custom_album_tp.total_pages
    }
  end
  def show
    @custom_album_setting = CustomAlbumSetting.first
    params = OrbitHelper.params
    custom_album = CustomAlbum.find_by_param(params[:uid])
    flag = show_desc?
    colors = CustomAlbumColor.where(:custom_album_id=> custom_album.id).pluck(:color,:custom_album_card_background_color,:custom_album_card_text_color)[0] rescue []
    images = custom_album.custom_album_images.asc(:order).collect do |a|
      alt_text = (a.description.blank? ? "custom_gallery image" : Nokogiri::HTML(a.description.to_s).text())
      {
        "image-description" => (flag ? a.description : ''),
        "image_short_description" => a.title,
        "alt_title" => alt_text,
        "link_to_show" =>  "#" + a.id.to_s,
        "thumb-src" => a.file.thumb.url,
        "thumb-large-src" => a.file.thumb_large.url,
        "mobile-src" => a.file.mobile.url,
        "theater-src" => a.file.theater.url,

        "custom_album_color" => iterate_data(colors[1],colors[0],@custom_album_setting.custom_album_card_background_color,'transparent'),
        "custom_album_card_text_color" => iterate_data(colors[2],@custom_album_setting.custom_album_card_text_color)
      }
    end
    {
      "images" => images,
      "data" => {"custom_album-title"=>custom_album.name,
                 "custom_album-description" => (flag ? "<p><span>#{custom_album.description}</span></p>" : "")}
    }
  end
  def iterate_data(*args)
    tmp = nil
    args.each do |arg|
      if !arg.blank? && arg != 'transparent'
        tmp = arg
        break
      end
    end
    tmp
  end
  def self.custom_widget_data
    @custom_configs = CustomAlbumConfig.all.to_a
    ac = ActionController::Base.new
    ac.render_to_string("custom_galleries/custom_widget_data",:locals=>{:@custom_data_field=>@custom_data_field,:@custom_configs=>@custom_configs,:@field_name=>@field_name})
  end
  def custom_album_widget
    @custom_album_setting = CustomAlbumSetting.first
    params = OrbitHelper.params
    tags = OrbitHelper.widget_tags.empty? ? ["all"] : OrbitHelper.widget_tags
    custom_album_tp = CustomAlbum.filter_by_widget_categories(OrbitHelper.widget_categories,false).filter_by_tags(tags)
    all_count = custom_album_tp.count
    page_data_count = OrbitHelper.widget_data_count
    no_order_count = custom_album_tp.where(:order.in=>[-1,nil]).count
    with_order_count = all_count - no_order_count
    with_order_total_pages = (with_order_count.to_f / page_data_count).ceil
    custom_albums_with_order = custom_album_tp.asc(:order).where(:order.ne=>-1).and(:order.ne=>nil).to_a rescue []
    page_no = (params[:page_no] || 1).to_i
    if page_no < with_order_total_pages
      custom_albums_no_order = []
      custom_albums_with_order = custom_albums_with_order[(page_no-1)*page_data_count...page_no*page_data_count]
    elsif page_no == with_order_total_pages
      if custom_albums_with_order.count == page_data_count
        custom_albums_no_order = []
      else
        custom_albums_no_order = custom_album_tp.desc(:created_at).where(:order.in=>[-1,nil]).page(nil).per(all_count)[0...(page_data_count - custom_albums_with_order.count)]
      end
    else
      custom_albums_with_order = []
      start_index = (page_data_count - (with_order_count % page_data_count) + page_data_count*(page_no - 1 - with_order_total_pages))
      custom_albums_no_order = custom_album_tp.desc(:created_at).where(:order.in=>[-1,nil]).page(nil).per(all_count)[start_index...(start_index+page_data_count)].to_a
    end
    custom_albums = custom_albums_with_order.concat(custom_albums_no_order)
    custom_album_color_map = CustomAlbumColor.where(:custom_album_id.in=> custom_albums.map{|v| v.id}).pluck(:custom_album_id,:color,:custom_album_card_background_color,:custom_album_card_text_color).map{|v| [v[0],v[1..-1]]}.to_h
    custom_galleries = custom_albums.collect.with_index do |a,i|
      doc = Nokogiri::HTML(a.description.to_s)
      alt_text = doc.text.empty? ? 'custom_gallery image' : doc.text.strip
      colors = custom_album_color_map[a.id]
      thumb_src = a.cover_path || "/assets/custom_gallery/default.jpg"
      cover_image = CustomAlbumImage.find(a.cover) rescue a.custom_album_images.first
      image_description = a.description
      image_short_description = a.name
      {
        "link_text" => a.name,
        "custom_album-name" => a.name,
        "custom_album-description" => a.description,
        "alt_title" => alt_text,
        "link_to_show" =>  OrbitHelper.widget_more_url + "/" + a.to_param + "#" + (cover_image.id.to_s rescue ""),
        "src" => thumb_src.gsub("thumb_",""),
        "thumb-src" => thumb_src,
        "thumb-large-src" => thumb_src.gsub("thumb_","thumb_large_"),
        "mobile-src" => thumb_src.gsub("thumb_","mobile_"),
        "theater-src" => thumb_src.gsub("thumb_","theater_"),
        "image_description" => image_description,
        "image_short_description" => image_short_description,
        "custom_album_color" => iterate_data(colors[1],colors[0],@custom_album_setting.custom_album_card_background_color,'transparent'),
        "custom_album_card_text_color" => iterate_data(colors[2],@custom_album_setting.custom_album_card_text_color),
        "i" => i
      }
    end
    {
      "images" => custom_galleries,
      "extras" => {"widget-title"=>"CustomGallery","more_url" => OrbitHelper.widget_more_url,"more_text"=>(locale == :en ? 'more' : '更多照片')}
    }
  end
  def widget
    @custom_album_setting = CustomAlbumSetting.first
    tags = OrbitHelper.widget_tags.empty? ? ["all"] : OrbitHelper.widget_tags
    custom_album_ids = CustomAlbum.filter_by_widget_categories(OrbitHelper.widget_categories,false).filter_by_tags(tags).pluck(:id)
    custom_album_color_map = CustomAlbumColor.where(:custom_album_id.in=> custom_album_ids).pluck(:custom_album_id,:color,:custom_album_card_background_color,:custom_album_card_text_color).map{|v| [v[0],v[1..-1]]}.to_h
    params = OrbitHelper.params
    counts = OrbitHelper.widget_data_count
    images = CustomAlbumImage.where({custom_album_id:{"$in"=>custom_album_ids}}).desc(:id).limit(counts *5).sample(counts)
    images = images.each_with_index.collect do |a,i|
      colors = custom_album_color_map[a.custom_album_id]
      alt_text = (a.description.blank? ? "custom_gallery image" : Nokogiri::HTML(a.description).text().strip)
      {
        "link_text" => "",
        "link_to_show" =>  OrbitHelper.widget_more_url + "/" + a.custom_album.to_param + "#" + a.id.to_s,
        "alt_title" => alt_text,
        "src" => a.file.url,
        "thumb-src" => a.file.thumb.url,
        "thumb-large-src" => a.file.thumb_large.url,
        "image_description" => a.description,
        "image_short_description" => a.title,
        "mobile-src" => a.file.mobile.url,
        "theater-src" => a.file.theater.url,
        "custom_album-name" => a.custom_album.name_translations[I18n.locale],
        "custom_album_color" => iterate_data(colors[1],colors[0],@custom_album_setting.custom_album_card_background_color,'transparent'),
        "custom_album_card_text_color" => iterate_data(colors[2],@custom_album_setting.custom_album_card_text_color),
        "i" => i
      }
    end
    {
      "images" => images,
      "extras" => {"widget-title"=>"CustomGallery","more_url" => OrbitHelper.widget_more_url,"more_text"=>(locale == :en ? 'more' : '更多照片')}
    }
  end
  def imgs(custom_album_id)
    custom_album = CustomAlbum.find(custom_album_id)
    tag_names = Array.new
    images = custom_album.custom_album_images.asc(:order)
    output =  Array.new
    images.each do |values|
      alt_text = (values.description.nil? || values.description == "" ? "custom_gallery image" : values.description)
      output << { _id:  values.id.to_s,
                  description: values.description,
                  title: values.title,
                  alt_title: alt_text,
                  url: values.file.url,
                  file: values.file.as_json[:file],
                  custom_gallery_custom_album_id: values.custom_album_id,
                  tags: values.tags}
    end
    return output
  end
  def theater
    if params[:id].include?('page=')
      custom_album = CustomAlbum.where(uid: params[:id].sub('page=','')).first
      custom_albumid = custom_album.id
      image = custom_album.custom_album_images.first
    else
      image = CustomAlbumImage.find(params[:id])
      custom_albumid = image.custom_album_id
      custom_album = CustomAlbum.find(custom_albumid)
    end
    images = custom_album.custom_album_images.asc(:order)
    data = {
      "custom_album" => custom_album,
      "image" => image.id.to_s,
      "images" => imgs(custom_albumid)
    }
    render :json => {"data" => data}.to_json
  end

  private

  def show_desc?
    tags = OrbitHelper.page_tags if tags.blank?
    tags = [tags].flatten.uniq
    flag = true
    tag_temp = Tag.all.select{|value| tags.include? value.id.to_s}
    tag_temp_length = 0
    tag_temp.each do |value|
      if value.name==I18n.t('custom_gallery.show_desc')
        flag = true
      elsif value.name==I18n.t('custom_gallery.not_show_desc')
        flag = false
      end
    end
    flag
  end
end