# frozen_string_literal: true
class Api::V1::BeliefsController < ApplicationController
  require 'stringio'

  skip_before_filter :verify_authenticity_token
  respond_to :json

  def auth_user(token)
    UserToken.find_by_auth_token(token).try(:user)
  end

  def index
    page_num = params[:page] || 1
    if request.headers['auth-token'].present?
      user = auth_user(request.headers['auth-token'])
      scopes = user.search_scopes
      trending = Belief.recent_with_scopes(get_search_scopes_from_params)
      beliefs = hidden_beliefs(trending, user)
      beliefs = Kaminari.paginate_array(beliefs).page(page_num).per(10)
      Belief.desposition_user = user
      data = { page: page_num.to_i + 1, beliefs: beliefs, user: user, role: user.roles, country: user.country, state: user.state, city: user.city, gender: user.gender, language: user.language, location: user.location }
      if beliefs.present?
        render status: 200, json: { success: true, info: 'All Beliefs', data: data }
      else
        render status: 401, json: { success: false, info: 'No Belief found' }
      end
    else
      beliefs = Belief.order('id DESC').page(page_num).per(10)
      data = { page: page_num.to_i + 1, beliefs: beliefs }
      if beliefs.present?
        render status: 200, json: { success: true, info: 'All Beliefs', data: data.as_json(all: true) }
      else
        render status: 401, json: { success: false, info: 'No Belief found' }
      end
    end
  end

  def all_list_dispose
    user = UserToken.find_by_auth_token(request.headers['auth-token']).user
    belief = Belief.find(params[:id])
    belief_disposition = belief.belief_dispositions.find_by_user_id(user)
    if belief_disposition.present?
      if params[:belief_disposition][:is_supported].present?
        belief_disposition.is_trashed = false
        belief_disposition.is_public = false
      end
      dispose = belief_disposition.update_attributes(params[:belief_disposition])
    else
      params[:belief_disposition][:user] = user
      params[:belief_disposition][:location_id] = user.location.id
      dispose = belief.belief_dispositions.create(params[:belief_disposition])
    end
    RestClient.get "#{Settings.similar_comment.url}/api/comments/comment_delete", params: { site_key: Settings.similar_comment.site_key, topic_key: belief.id, author_key: user.author_hash_key } if user.author_hash_key.present?
    render status: 200,
           json: { success: true,
                   info: 'Belief Disposition is managed!',
                   data: { belief: belief,
                           belief_dispositions: dispose } }
  end

  def create
    user = auth_user(request.headers['auth-token'])
    if params[:belief][:belief_image].present? || params[:belief][:youtube_url].present?
      image_belief, video_image_belief = Belief.video_image(params) if params[:system_video].present?
      youtube_image_belief = Belief.youtube_image(params) if params[:belief][:youtube_url].present?
      belief_image = Belief.belief_image_video(params) if params[:belief][:belief_image].present?
      params[:belief][:belief_image] = video_image_belief.present? ? video_image_belief : belief_image.present? ? belief_image : []
      params[:belief][:video_image] = image_belief if image_belief.present?
      params[:belief][:youtube_image] = youtube_image_belief if youtube_image_belief.present?
      belief = user.beliefs.new(params[:belief])
      if belief.save
        FileUtils.rm_rf 'public/uploads/video'
        is_public = belief.show_author ? true : params[:is_public]
        dispositions = belief.belief_dispositions.create(user: user, location: user.location, is_supported: true, is_public: is_public)
        render status: 200,
               json: { success: true,
                       info: 'Belief is create',
                       data: { belief: belief,
                               user: user } }
      else
        render status: 401,
               json: { success: false,
                       info: belief.errors.full_messages
                        }
      end
    else
      render status: 401,
             json: { success: false,
                     info: 'Please Add Image or Video first'
                }
    end
  end

  def show
    user = UserToken.find_by_auth_token(request.headers['auth-token']).user
    begin
      belief = Belief.find(params[:belief])
    rescue ActiveRecord::RecordNotFound => e
      belief = nil
    end
    Belief.desposition_user = user
    if belief.present?
      agree  = belief.try(:belief_dispositions).where(is_supported: true)
      dis_agree = belief.try(:belief_dispositions).where(is_supported: false)
      render status: 200,
             json: { success: true,
                     info: 'Please see your Belief ',
                     data: { belief: belief,
                             support: JSON.parse(agree.to_json(include: { location: { only: [:latitude, :longitude] } })),
                             oppose: JSON.parse(dis_agree.to_json(include: { location: { only: [:latitude, :longitude] } })),
                             agree: agree.count,
                             dis_agree: dis_agree.count
                                 }
                      }
    else
      render status: 401,
             json: { success: false,
                     info: 'belief not found'
                      }
    end
  end

  def search
    user = auth_user(request.headers['auth-token'])
    if params[:text].present?
      Belief.search(params['text']).first
      search_scopes = get_search_scopes_from_params
      beliefs = Belief.search_with_scopes search_scopes, params[:text]
      beliefs = hidden_beliefs(beliefs, user)
      beliefs = Kaminari.paginate_array(beliefs).page(params[:page] || 1).per(10)
      if beliefs.present?
        page = params[:page] || 1
        render status: 200,
               json: { success: true,
                       info: 'Belief are',
                       data: { page: page.to_i + 1, beliefs: beliefs } }
      else
        render status: 401,
               json: { success: false,
                       info: 'Try search with different text'
                        }
      end
    else
      render status: 401,
             json: { success: false,
                     info: 'Please enter some text'
                      }
    end
  end

  def category_search
    page_num = params[:page] || 1
    user = UserToken.find_by_auth_token(request.headers['auth-token']).user
    belief = Belief.joins(:locations).joins(:user).joins(:beliefs_categories).where('is_publish = ?', true).where('beliefs_categories.category_id=?', params[:category]).group('beliefs.id')
    belief = hidden_beliefs(belief, user)
    belief = Kaminari.paginate_array(belief).page(page_num).per(10)
    Belief.desposition_user = user
    if belief.present?
      render status: 200,
             json: { success: true,
                     info: 'Beliefs are',
                     data: { page: page_num.to_i + 1, beliefs: belief } }
    else
      render status: 401,
             json: { success: false,
                     info: 'Beliefs are not present' }
    end
  end

  def sort_search
    user = UserToken.find_by_auth_token(request.headers['auth-token']).user
    if params[:trending] == 'Trending'
      trends = trending_beliefs(user)
    elsif params[:trending] == 'Most Popular'
      trends = popular_beliefs(user)
    elsif params[:trending] == 'Just Added'
      trends = recent_beliefs(user)
    end
    trends = hidden_beliefs(trends, user)
    Belief.desposition_user = user
    if trends
      page = params[:page] || 1
      render status: 200,
             json: { success: true,
                     info: 'Beliefs are',
                     data: { page: page.to_i + 1, trends: trends } }
    else
      render status: 401,
             json: { success: false,
                     info: 'Beliefs are not present' }
    end
  end

  def trending_beliefs(user)
    if user
      beliefs = Belief.trending_with_scopes(get_search_scopes_from_params)
    else
      beliefs = Belief.top5_trending
    end
    beliefs = beliefs.page(params[:page] || 1)
  end

  def popular_beliefs(user)
    page_num = params[:page] || 1
    if user
      beliefs = Belief.popular_with_scopes(get_search_scopes_from_params)
      beliefs = ten_visiable_beliefs(beliefs, user) if page_num.to_i == 1
    else
      beliefs = Belief.top5_popular
    end
    beliefs = Kaminari.paginate_array(beliefs).page(page_num).per(10) unless page_num.to_i == 1
    beliefs
  end

  def recent_beliefs(user)
    page_num = params[:page] || 1
    if user
      beliefs = Belief.recent_with_scopes(get_search_scopes_from_params)
      beliefs = ten_visiable_beliefs(beliefs, user) if page_num.to_i == 1
    else
      beliefs = Belief.top5_recent
    end
    beliefs = Kaminari.paginate_array(beliefs).page(page_num).per(10) unless page_num.to_i == 1
    beliefs
  end

  def get_search_scopes_from_params
    # collect any search scope params
    current_user = auth_user(request.headers['auth-token'])
    search_scopes = {}
    if current_user
      if current_user.scope == 'My Country'
        params[:country] = current_user.country if params[:country].blank?
      elsif current_user.scope == 'My State/Region'
        params[:country] = current_user.country if params[:country].blank?
        params[:state] = current_user.state if params[:state].blank?
      elsif current_user.scope == 'My Town/City'
        params[:country] = current_user.country if params[:country].blank?
        params[:state] = current_user.state if params[:state].blank?
        params[:city] = current_user.city if params[:city].blank?
      elsif current_user.scope == 'My Neighborhood'
        params[:country] = current_user.country if params[:country].blank?
        params[:state] = current_user.state if params[:state].blank?
        params[:city] = current_user.city if params[:city].blank?
        params[:postal_code] = current_user.postal_code if params[:postal_code].blank?
      end
    end
    if params[:country].present?
      search_scopes['country'] = params[:country]
      if params[:state].present?
        search_scopes['state'] = params[:state]
        if params[:city].present?
          search_scopes['city'] = params[:city]
          if params[:postal_code].present?
            search_scopes['postal_code'] = params[:postal_code]
          end
        end
      end
    end
    search_scopes
  end

  def ten_visiable_beliefs(beliefs, user)
    hidden_blfs = BeliefDisposition.hidden_belief(user.id)
    count = 0
    visiable_beliefs = []
    beliefs.each do |belief|
      count += 1 unless hidden_blfs.include?(belief.id)
      break if count > 10
      visiable_beliefs << belief
    end
    visiable_beliefs
  end

  def comment
    comment = RestClient.get "#{Settings.similar_comment.url}/api/comments/comment_all", params: { site_key: Settings.similar_comment.site_key, topic_key: params[:topic_key] }
    render status: 200,
           json: { comment: JSON.parse(comment) }
  end

  def comment_create
    user = UserToken.find_by_auth_token(request.headers['auth-token']).user
    comment = RestClient.get "#{Settings.similar_comment.url}/api/comments/comment_add", params: { site_key: Settings.similar_comment.site_key, topic_key: params[:topic_key], author_key: user.author_hash_key, content: params[:content], type: params[:type], topic_title: params[:topic_title], author_name: user.name, url_topic: "#{request.host}/beliefs/#{params[:topic_key]}" }
    render status: 200,
           json: { comment: JSON.parse(comment) }
  end

  def flag_belief
    belief = Belief.find(params[:belief_id])
    if belief && auth_user(request.headers['auth-token'])
      flag = belief.flag_belief(auth_user(request.headers['auth-token']), params[:text])
    end
    render json: { flag: 'Successfully created' }
  end

  def file_in_belief
    dispositions = BeliefDisposition.where(user_id: auth_user(request.headers['auth-token']), belief_id: params[:belief_id])
    disposition = dispositions[0]

    if disposition
      disposition.is_filed_in = if disposition.is_filed_in == true
                                  false
                                else
                                  true
                                end
      disposition.save
    end
    render json: { disposition: disposition }
  end

  def hidden_beliefs(beliefs, user)
    trashed_beliefs = BeliefDisposition.select(:belief_id).where(user_id: user.id, is_trashed: true)
    trashes = []
    trashed_beliefs.each do |o|
      trashes.push o.belief_id
    end
    filed_in_beliefs = BeliefDisposition.select(:belief_id).where(user_id: user.id, is_filed_in: true)
    filed_ins = []
    filed_in_beliefs.each do |o|
      filed_ins.push o.belief_id
    end
    filed_ins = Belief.where(id: filed_ins)
    trashes = Belief.where(id: trashes)
    beliefs -= trashes if params[:trash].blank?
    beliefs -= filed_ins if params[:filled].blank?
    beliefs
  end

  def get_supported_dispositions
    belief_suppoted_users = []
    belief_not_public = []
    dispositions = BeliefDisposition.joins(:location).where('belief_id = ? and (is_trashed IS NULL or is_trashed = ?) and (is_supported = ? OR is_supported IS NULL)', params[:id], false, true)
    get_search_scopes_from_params.each do |key, value|
      dispositions = dispositions.where('locations.' + key + ' = ? ', value)
    end

    dispositions.each do |disposition|
      if disposition.is_public?
        belief_suppoted_users << { user_slug: disposition.user ? disposition.user.slug : '',
                                   belief: disposition.belief,
                                   privacy: disposition.is_public?,
                                   image: disposition.user ? (disposition.user.profile_image_api_url || '/assets/no_avatar92.png') : '/assets/no_avatar92.png'
        }
      else
        belief_not_public << disposition.is_public?
      end
    end
    render status: 200, json: { public_belief: belief_suppoted_users,
                                non_public_belief: belief_not_public.count }
  end

  def get_opposed_dispositions
    belief_opposed_users = []
    belief_not_public = []
    dispositions = BeliefDisposition.joins(:location).where('belief_id = ? and (is_trashed IS NULL or is_trashed = ?) and (is_supported = ? OR is_supported IS NULL)', params[:id], false, false)
    get_search_scopes_from_params.each do |key, value|
      dispositions = dispositions.where('locations.' + key + ' = ? ', value)
    end
    dispositions.each do |disposition|
      if disposition.is_public?
        belief_opposed_users << { user_slug: disposition.user ? disposition.user.slug : '',
                                  belief: disposition.belief,
                                  privacy: disposition.is_public == true ? false : true,
                                  image: disposition.user ? (disposition.user.profile_image_api_url || '/assets/no_avatar92.png') : '/assets/no_avatar92.png'
        }
      else
        belief_not_public << disposition.is_public?
      end
    end
    render status: 200, json: { public_belief: belief_opposed_users,
                                non_public_belief: belief_not_public.count }
  end
end
