class ApplicationController < ActionController::Base

	before_filter :require_login

	def require_login
		if authenticated?
			create_new_authentication()

            if controller_name != 'chat' and (controller_name != 'sessions' and action_name != 'destroy')
                redirect_to chat_path
            end
		else
			unless controller_name == 'sessions' && (action_name == 'new' || action_name == 'create')
                redirect_to root_url, flash: {error: I18n.t('login.access-denied')}
			end
		end
	end

	protected

	def authenticated?
        @token = Token.authenticate(session)
	end

	def create_new_authentication(user_credentials = nil)
        if @token
            user_id = @token.user_id
            @token.delete
        else
            user_id = nil
        end

        @token = Token.new

        save_session(user_id, user_credentials)
    end

    def remove_session
        reset_session()
        cookies.delete :iv
        cookies.delete :key
    end

    private

    def save_session(user_id, user_credentials)
        session[:token]      = Token.generate_token()
        session[:created_at] = Time.now
        session[:ip]         = request.remote_ip

        if user_credentials
            encrypted_pass = Security::encrypt(user_credentials[:password])
            #TODO: pridat do sifry aj nieco z konfigov
            cookies[:key] = Security::cipher_key
            cookies[:iv]  = Security::cipher_iv

            user = create_new_user(user_credentials)
            user.update_pass(user_credentials[:jid], encrypted_pass)
            user_id = user.id
        end

        @token.save_session(session, user_id)
    end

    def create_new_user(user_credentials)
        jid  = user_credentials[:jid]
        user = User.existing_jid(jid) || User.create_jid(jid)
    end
end