class UserController < Users::ApplicationController
  before_action :allow_all_origins
  layout 'user/foundation'
  #layout 'phone'

  alias :list :active_list

  def index
    handle_message_params
  end

  # POST /user/create_list {table_id: 1234}
  #DEPRICATED, see order_selected_products, this one now handles list creation as well
  #def create_list
    #render nothing: true and return unless current_user.present?
    #@table = Table.find(params[:table_id])
    #if @table.occupied?
      #respond_to do |format|
        #format.html { redirect_to user_root_path, alert: t('messages.table_is_occupied') }
        #format.json { render json: json_alert('messages.table_is_occupied')}
      #end
    #else
      #if @list = List.from_table( @table, current_user )
      #end
      #respond_to do |format|
        #format.html { redirect_to user_list_products_path }
        #format.json { render json: json_notice('messages.new_list_created')}
      #end
    #end
  #end

  # GET /user/table_info.json
  # used for moving table request
  # TODO wrap logic of actions
  # - table_info
  # - move_table
  # into separate class and implement security in a non stupid way as it is now
  def table_info
    respond_to do |format|
      format.json do
        render json: json_alert('messages.table_not_found') and return unless params[:table_id].present?
        @table = Table.find(params[:table_id])
        res = {}
        res[:occupied] = @table.occupied?
        res[:reserved] = @table.reserved?
        res[:supplier_closed] = @table.supplier.closed?
        if list.present?
          res[:other_supplier] = true if list.supplier_id != @table.supplier_id
          res[:current_table_id] = list.table_id
        end
        render json: res
      end
    end
  end

  # POST /user/move_table.json
  # used to move the table
  # TODO wrap logic of actions
  # - table_info
  # - move_table
  # into separate class and implement security in a non stupid way as it is now
  def move_table
    render json: json_alert('messages.no_active_list', list_active: false) and return unless list.present?
    render json: json_alert('messages.table_not_found') and return unless params[:table_id].present?
    @table = Table.find(params[:table_id])
    if @table.occupied?
      render json: {occupied: true}
    elsif @table.reserved?
      render json: {reserved: true}
    elsif list.supplier_id != @table.supplier_id
      res[:other_supplier] = true if list.supplier_id != @table.supplier_id
      res[:current_table_id] = list.table_id
    else
      list.move_to_table! @table
      render json: {occupied: false, reserved: false}
    end
  end

  # GET /suppliers/1/product_list
  # GET /suppliers/1/product_list.json
  def list_products
    respond_to do |format|
      format.html do
        redirect_to(user_root_path(message: 'the_list_has_been_closed')) and return unless list
        @supplier = list.supplier
        handle_message_params
      end
      format.json do
        unless list
          render json: {not_present: true} and return
        end
        @supplier = list.supplier
        h = ProductCategory.for_user(current_user, table: list.table, list: list, supplier: @supplier) # list is performance parameter
        render json: h
        #products = list.supplier.products
        #product_categories = list.supplier.product_categories
        #other = product_categories.find(&:other?) || (product_categories << ProductCategory.other).last # Container for non categorized products

        #product_categories.sort_by!{|p| p.product_category.try(:position) || 90000}
        #h = {table_number: list.table_number, supplier_name: @supplier.name}
        #h[:categories] = product_categories.map{|pc| {pc.name => pc.product_ids.map{|p| p.as_json}}}
        #){|h, p| n = p.product_category.try(:name) || 'other'; h[n] ||= []; h[n] << p; h}
        #render json: h
      end
    end
  end

  def list_products_for_table
    respond_to do |format|
      format.html do
      end
      format.json do
        render json: json_alert('messages.table_not_found') and return unless params[:table_id].present?
        @table = Table.find(params[:table_id])
        h = ProductCategory.for_user(current_user, table: @table)
        render json: h
      end
    end
  end

  # POST /user/join_occupied_table
  def request_to_join_occupied_table
    render json: json_alert('messages.table_not_found') and return unless params[:table_id].present?
    @table = Table.find(params[:table_id])
    if @list = @table.active_list
      @list.send_table_join_request_for_user! current_user
    end
    render nothing: true
  end

  # POST /user/reject_join_request?user_id=1
  def reject_join_request
    render js: '' and return unless params[:user_id].present?
    list && list.reject_join_request_for_user!(params[:user_id])
    render js: ''
  end

  # POST /user/approve_join_request?user_id=1
  def approve_join_request
    render js: '' and return unless params[:user_id].present?
    @user = User.find(params[:user_id])
    list && list.approve_join_request_for_user!(@user)
    render nothing: true
  end

  # POST /user/check_table_join_status.json table_id:12345
  def check_table_join_status
    render json: json_alert('messages.table_not_found') and return unless params[:table_id].present?
    @table = Table.find(params[:table_id])
    if @list = @table.active_list
      if @list.user_ids.include?(current_user.id)
        render json: {approved: true}
      elsif @list.join_request_user_ids.include?(current_user.id)
        render json: {waiting: true}
      else
        render json: {rejected: true}
      end
    else
      render json: {rejected: true}
    end
  end

  # GET /user/current_list.json
  # Information about the currently active list
  # This information includes detailed order information
  def active_list
    respond_to do |format|
      format.html do
        redirect_to(user_root_path, alert: t('messages.there_is_no_list_active')) and return unless list.present?
      end
      format.json do
        render json: js_alert(t('messages.the_list_has_been_closed')) and return unless list.present?
        render json: list.with_orders_and_join_requests_and_supplier_info_as_json
      end
    end
  end

  # GET /user/list_info.json
  # Information about the currently active list
  # Fast version to verify wether the is is still currently active
  # for handle_active_list
  def list_info
    respond_to do |format|
      format.json do
        if list.present?
          if !list.try(:active?)
            current_user.list_is_closed!
            render json: json_response(list_active: false)
            return
          else
            render json: json_response(list.serialized_with_status_join_requests_and_supplier_counters)
          end
        else
          render json: json_response(not_present: true)
        end
      end
    end
  end

  def feedback
    UserFeedback.create(user_id: current_user.id, content: params[:feedback].to_s)
    render json: {}
  end

  # POST /user/needs_help.json
  def needs_help
    respond_to do |format|
      format.json do
        render json: json_alert('messages.no_active_list', list_active: false) and return unless list.present?
        list.needs_help!
        render json: list.as_json.merge(list_active: list.active?)
      end
    end
  end

  # POST /user/list_needs_payment.json
  def list_needs_payment
    respond_to do |format|
      format.json do
        render json: json_alert('messages.no_active_list', list_active: false) and return unless list.present?
        list.needs_payment!
        render json: list.as_json.merge(list_active: list.active?)
      end
    end
  end

  ##
  # Displays the closed lists of the user
  # GET /user/list_history
  #def list_history
    #respond_to do |format|
      #format.html {}
      #format.json do
        #@lists = List.for_user(current_user, page: params[:page], per_page: params[:per_page].presence || 14)
        #@lists.include_relation(:supplier)
        #render json: @lists.inject(lists: [], current_page: @lists.current_page, num_pages: @lists.num_pages, total_count: @lists.total_count){|h, l| h[:lists] << l.as_json.merge(supplier_name: l.supplier.name); h}
      #end
    #end
  #end

  ##
  # Displays a closed list of the user
  # GET /user/list_history/:list_id
  #def history_list
    #respond_to do |format|
      #format.html do
      #end
      #format.json do
        #@list = List.find(params[:list_id])
        #render json: json_alert('messages.illegal_history_list_attempt') and return unless @list.user_ids.include?(current_user.id)
        #if params[:list_closed].present? && current_user.active_list_id == @list.id
          #current_user.list_is_closed!
          #flash.now[:notice] = t('messages.the_list_has_been_closed', list: List.model_name.human)
        #end
        #render json: @list.with_orders_as_json.merge(supplier_name: @list.supplier.name)
      #end
    #end
  #end


  # POST /user/order_selected_products.json
  #def order_selected_products
    #if list.present?
      #@list = list
    #else
      #render json: json_alert('messages.table_not_found') and return unless params[:table_id].present?
      #@table = Table.find(params[:table_id])
      #if @table.occupied?
        #render json: json_alert('messages.table_is_occupied', location: :join_occupied_table, location_params: {table_id: @table.id})
      #else
        #if @list = List.from_table( @table, current_user )
        #else
          ##TODO handle second list creation for user
        #end
      #end
    #end
    #respond_to do |format|
      #format.html do
        #redirect_to(user_root_path, alert: t('messages.cannot_order_on_non_active_list')) and return unless @list.active?
        #@list.place_order products: params[:products], user: current_user
        #redirect_to user_root_path, notice: t('messages.order_is_placed')
      #end
      #format.json do
        #render json: json_alert('messages.cannot_order_on_non_active_list') and return unless @list.active?
        ## Todo, better document and uniform this
        #@list.place_order products: (params[:order] || params[:products]), user: current_user
        #render json:  json_notice('messages.order_is_placed', location: :active_list)
      #end
    #end
  #end

  def obtain_token
    redirect_to user_omniauth_authorize_path('facebook') and return unless current_user.present?
    # redirect_to case platform
    # when 'android' then "file:///android_asset/user/index.html?user_id=#{current_user.id}&auth_token=#{current_user.authentication_token}"
    #   when
    #   else user_root_path(user_id: current_user.id, auth_token: current_user.authentication_token)
    #   end
    # return
    respond_to do |format|
      format.html { render layout: 'user/obtain_token' }
      format.json do
        render json: json_response(ok: false, status: 401) and return unless params[:user].present? && params[:user][:email].present? && params[:user][:password].present?
        user = User.find_by_email(params[:user][:email])
        render json: json_response(ok: false, status: 401) and return unless user
        render json: json_response(ok: false, status: 401) and return unless user.valid_password?(params[:user][:password])
        user.ensure_authentication_token
        sign_in user
        render json: json_response(ok: true, auth_token: user.authentication_token, user_id: user.id)
      end

    end
  end

end
