class PersonalBooksController < ApplicationController
  def index
    params = OrbitHelper.params
    page_data_count = OrbitHelper.page_data_count
    books = Book.where(is_hidden: false).sort_for_frontend.page(OrbitHelper.params[:page_no]).per(page_data_count)
    page = Page.where(page_id: params[:page_id]).first rescue nil

    if page.custom_string_field == 'table'
      fields_to_show = page.custom_array_field rescue []
      if fields_to_show.blank?
        fields_to_show = %w[
          authors
          book_title
          extracted_chapters
          publisher
          isbn
          publish_date
        ]
      end
    else
      fields_to_show = %w[
        year
        book_title
      ]
    end
    if !params[:selectbox].nil?
      books_temp = Book.where(is_hidden: false).sort_by { |tp| [-tp[:year].to_i, -tp[:publication_date].to_i] }
      case params[:selectbox]
      when 'book_title', 'extracted_chapters', 'default'
        search_temp = if params[:selectbox] == 'default'
                        'book_title'
                      else
                        params[:selectbox]
                      end
        if page.custom_string_field == 'table'
          books_show = books_temp.select { |value| search_all_words(value.send(search_temp), params[:keywords]) }
        else
          books_show = books_temp.select { |value| search_all_words(value.create_link, params[:keywords]) }
        end
      when 'publish_date', 'publication_date'
        books_show = books_temp.select { |value| search_all_words((value.send(params[:selectbox]).strftime('%Y/%m/%d') rescue ''), params[:keywords]) }
      when 'author_type'
        books_show = books_temp.select { |value| search_all_words(value.book_author_types.collect(&:title).join(', '), params[:keywords]) }
      when 'book_paper_type'
        books_show = books_temp.select { |value| search_all_words((value.book_type.title rescue ''), params[:keywords]) }
      when 'language'
        books_show = books_temp.select { |value| search_all_words((!value.language.nil? ? t(value.language.to_s) : ''), params[:keywords]) }
      else
        books_show = books_temp.select { |value| search_all_words(value.send(params[:selectbox]).to_s, params[:keywords]) }
      end
      page_to_show = params[:page_no].nil? ? 1 : params[:page_no].to_i
      books = books_show[(page_to_show - 1) * page_data_count...page_to_show * page_data_count]
      books_total_pages = (books_show.length / page_data_count.to_f).ceil
    else
      books_total_pages = books.total_pages
    end
    book_list = []
    books.each do |book|
      t = []
      fields_to_show.each do |fs|
        case fs
        when 'book_title', 'extracted_chapters'
          t << if page.custom_string_field == 'table'
                 { 'value' => "<a href='#{OrbitHelper.url_to_show(book.to_param)}'>#{book.send(fs)}</a>" }
               else
                 { 'value' => "<a href='#{OrbitHelper.url_to_show(book.to_param)}'>#{book.create_link}</a>" }
               end
        when 'publish_date', 'publication_date'
          t << { 'value' => (!book.send(fs).nil? ? book.send(fs).strftime('%Y/%m') : '' rescue '') }
        when 'author_type'
          t << { 'value' => (book.book_author_types.collect(&:title).join(', ') rescue '') }
        when 'language'
          t << { 'value' => (!book.language.nil? ? t(book.language.to_s) : '') }
        when 'book_paper_type'
          t << { 'value' => (book.book_type.title rescue '') }
        else
          t << { 'value' => (book.send(fs) rescue '') }
        end
      end
      book_list << { 'books' => t }
    end
    choice_show = []
    headers = []
    fields_to_show.each do |fs|
      col = 2
      col = 3 if fs == 'paper_title'
      headers << {
        'head-title' => t("personal_book.#{fs}"),
        'col' => col
      }
      choice_show << t("personal_book.#{fs}")
    end
    choice_value = fields_to_show
    choice_value.unshift('default')
    choice_select = choice_value.map { |iter| iter == params[:selectbox] ? 'selected' : '' }
    choice_select = choice_select.map { |value| { 'choice_select' => value } }
    choice_value = choice_value.map { |value| { 'choice_value' => value } }
    choice_default = t('personal_book.select_class')
    choice_show.unshift(choice_default)
    choice_show = choice_show.map { |value| { 'choice_show' => value } }
    choice = choice_value.zip(choice_show, choice_select)
    choice = choice.map { |value| value.inject :merge }
    select_text = t('personal_book.search_class')
    search_text = t('personal_book.word_to_search')
    {
      'book_list' => book_list,
      'extras' => { 'widget-title' => t('module_name.book'),
                    'url' => '/' + params[:locale] + params[:url],
                    'select_text' => select_text,
                    'search_text' => search_text,
                    'search_value' => params[:keywords] },
      'headers' => headers,
      'total_pages' => books_total_pages,
      'choice' => choice
    }
  end

  def show
    params = OrbitHelper.params
    plugin = Book.where(is_hidden: false).find_by(uid: params[:uid])
    fields_to_show = %w[
      year
      book_title
      authors
      book_paper_type
      extracted_chapters
      publisher
      publish_date
      pages
      editor
      author_type
      number_of_authors
      isbn
      url
      file
      publication_date
      language
    ]

    { 'plugin_datas' => plugin.get_plugin_data(fields_to_show) }
  end

  def get_fields_for_index
    @page = Page.find(params[:page_id]) rescue nil
    @fields_to_show = %w[
      year
      book_title
      authors
      book_paper_type
      extracted_chapters
      publisher
      publish_date
      pages
      editor
      author_type
      number_of_authors
      isbn
      url
      publication_date
      language
    ]
    @fields_to_show = @fields_to_show.map { |fs| [t("personal_book.#{fs}"), fs] }
    @default_fields_to_show = %w[
      authors
      book_title
      extracted_chapters
      publisher
      isbn
      publish_date
    ]
    render layout: false
  end

  def save_index_fields
    page = Page.find(params[:page_id]) rescue nil
    page.custom_array_field = params[:keys]
    page.save
    render json: { 'success' => true }.to_json
  end

  private

  def search_all_words(target, word)
    target = target.upcase
    words = word.upcase.split(' ')
    words.select { |value| target.include? value } == words
  end
end