class OrganisationController < ApplicationController
  before_action :authenticate_user!
  before_action :set_default,:except => [:new, :index, :create, :org_edit, :settings, :domain_exist, :live_domain_exist, :search]
  load_and_authorize_resource :class => Organisation
  skip_load_resource :only => [:set_default,:update,:destroy, :create, :org_edit, :settings]
  
  def new
    @organisation = Organisation.new
  end

  def index
    @organisation = current_user.organisation
    @gateway_configs = @organisation.gateway_configs
    @gateway_config = GatewayConfig.new
    if params[:id].present?
      @gateway_config = @gateway_configs.find_by_id(params[:id])
    end
  end

  def settings
    org_edit
  end

  def org_edit
    if current_user.is_super_admin
      @organisation = Organisation.find_by_id(params[:id])
    else
      @organisation = current_user.organisation
    end
  end

  def update
    if params[:organisation].present? && !@gateway_config
      if params["organisation"].present? && params["organisation"]["users_attributes"].present?
        user_attributes = params["organisation"]["users_attributes"]["0"]
        if user_attributes["password"].blank? && user_attributes["password_confirmation"].blank? 
          user_attributes.delete("password")
          user_attributes.delete("password_confirmation")
        end
      end
      @organisation = Organisation.find_by_id(params[:id]) if current_user.is_super_admin
      @organisation = current_user.organisation if !current_user.is_super_admin
      if @organisation.update_attributes(user_params)
        flash[:success] = 'Successfully updated organisation'
      else
        flash[:notice] = "#{@organisation.errors.values[1]}"
      end
      redirect_to admin_assume_users_path if current_user.is_super_admin
      redirect_to settings_path if !current_user.is_super_admin
    else
      if params[:gateway_type] == '1'
        config_hash = {'a_id' => params[:account],"ph_no" => params[:phone_number],'auth_token' => params[:auth_token]}
      else
        config_hash = {'address' => params[:address],"port" => params[:port],'domain' => params[:domain],'u_name' => params[:username],'pwd' => params[:password],'auth_type' => params[:auth_type]}
      end
      @gateway_config.update_attributes({gateway_type: params[:gateway_type],gateway: params[:gateway],config_hash: config_hash,is_enabled: params[:is_enabled]})
      flash[:success] = 'Successfully updated Gateway Configuration'
      redirect_to organisation_index_path
    end
  end

  def create
    if params[:organisation].present?
      @org = Organisation.new(user_params)
      @org.users.first.from_sa = true
      if @org.save
        userid = @org.users.first.id
        flash[:success] = 'Successfully created organisation'
        url = request.base_url +  "/users/sign_in"
        UserMailer.delay.user_approved(userid,url)
      else
        flash[:notice] = "#{@org.errors.values[1]}"
      end
      return redirect_to admin_assume_users_path
    else
      if params[:gateway_type] == '1'
        config_hash = {'a_id' => params[:account],"ph_no" => params[:phone_number],'auth_token' => params[:auth_token]}
      else
        config_hash = {'address' => params[:address],"port" => params[:port],'domain' => params[:domain],'u_name' => params[:username],'pwd' => params[:password],'auth_type' => params[:auth_type]}
      end
      g_config = current_user.organisation.gateway_configs.new(gateway_type: params[:gateway_type],gateway: params[:gateway],config_hash: config_hash,is_enabled: params[:is_enabled])
      if g_config.save
        flash[:success] = 'Successfully created Gateway Configuration'
      else
        flash[:notice] = 'Oops!, Problem creating Gateway Configuration,Please try after some time'
      end
      return redirect_to organisation_index_path
    end
  end

  def destroy
    if @gateway_config.destroy
      flash[:success] = 'Successfully deleted Gateway Configuration'
    else
      flash[:notice] = 'Oops!, Problem deleting Gateway Configuration,Please try after some time'
    end
    redirect_to organisation_index_path
  end

  def change_enable_state
    render :json=> {:status=>false,:reload => false}.to_json and return if @gateway_config.blank?
    @organisation = current_user.organisation
    @gateway_configs = @organisation.gateway_configs.find_by_id(params[:gateway_config_id])
    if @gateway_configs.present?
      state = params[:is_enabled] == 'true' ? 'true' : 'false'
      @gateway_configs.update_attributes({is_enabled: state})
      if @gateway_configs.save!
        render :json=> {:status=>'success',:msg=>'Successfully updated Gateway status',:reload => true}.to_json and return
      else
        render :json=> {:status=>'error',:msg=>'Oops! Problem updating status Please try after some time',:reload => false}.to_json and return
      end
    else  
    end  
  end
  
  def domain_exist
    organisation = Organisation.where("organisation_domain" => params[:organisation_domain]).first
    status = organisation.blank? || organisation.id.to_s.eql?(params[:organisation_id]) ? true : false
    render :json => {value: status}
  end

  def live_domain_exist
    organisation = Organisation.where("live_domain" => params[:live_domain]).first
    status = organisation.blank? || organisation.id.to_s.eql?(params[:organisation_id]) ? true : false
    render :json => {value: status}
  end


  def search
    search = params[:search]
    search_data = {}
    network_param = params[:location_network]
    filter_params = (params[:filter] || "").split(',')

    if search
      if network_param.present?
        networks = @user.organisation.location_networks.where("network_name LIKE ?", "%#{network_param[:name]}%") if network_param[:name]
        networks = @user.organisation.location_networks.where(id: network_param[:id]) if network_param[:id]
        if networks.present?
          inventories = @user.organisation.router_inventories.where("(mac_id LIKE ? OR name LIKE ?) AND location_network_id IN (?)", "%#{search}%", "%#{search}%", networks.map(&:id)) if (filter_params.blank? || filter_params.include?('devices'))
          network_ssids = NetworkSsid.where("ssid_name LIKE ? AND location_network_id IN (?)", "%#{search}%", networks.map(&:id)) if (filter_params.blank? || filter_params.include?('network_ssids'))
        end
      else
        networks = @user.organisation.location_networks.where("network_name LIKE ?", "%#{search}%")
        network_ssids = NetworkSsid.where("ssid_name LIKE ? AND location_network_id IN (?)", "%#{search}%", @user.organisation.location_networks.map(&:id)) if(filter_params.blank? || filter_params.include?('network_ssids'))
        inventories = @user.organisation.router_inventories.where("mac_id LIKE ? OR name LIKE ?", "%#{search}%", "%#{search}%") if(filter_params.blank? || filter_params.include?('devices'))
      end
      search_data[:location_networks] = networks.map{|n| n.json_build.except(:device)} if networks.present? && (filter_params.blank? || filter_params.include?('location_networks'))
      search_data[:network_ssids] = network_ssids.map{|n| n.json_build} unless network_ssids.blank?
      search_data[:devices] = inventories.map{|n| n.json_build} unless inventories.blank?

      render json: { data: search_data, status: 200 }, status: 200
    else
      render json: { error: "Search parameter is required.", status: 400 }, status: 400
    end
  end

  private


  def set_default
    if !params[:organisation]
      organisation = current_user.organisation
      @gateway_config = organisation.gateway_configs.find_by_id(params[:id] || params[:gateway_config_id])
      if @gateway_config.blank?
        flash[:notice] = 'Oops!, selected Gateway Configuration not found'
        redirect_to organisation_index_path
      end
    end
  end

  def user_params
    params.require(:organisation).permit(:organisation_name, :organisation_domain, :live_domain, :organisation_support_email, :header_bg_color, :sidebar_bg_color, :footer_bg_color, :footer_font_bg_color, :organisation_logo, :branding, users_attributes: [:full_name, :email, :password, :password_confirmation, :phone_number, :id, :_destroy])
  end

end
