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
            session[:users] = {} unless session[:users]

            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

            session[:users][user_credentials[:jid]] = encrypted_pass
        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)

        user.id
    end
end