def export_calendar_for_user(cal_user_id=None, filename="export"):
    """
    Create and export iCalendar file with the meetings of the chosen user

    :param cal_user_id: User ID to create calendar for
    :param filename: Filename for the ics file
    :return: ics file wrapped in a response
    """
    if cal_user_id is None:
        # Defaults to current user
        cal_user_id = current_user.id

    meeting_list = Meeting.get_user_meetings(cal_user_id)
    tz = timezone(app.config['TIMEZONE'])
    cal = Calendar()
    for meeting in meeting_list:
        event = Event()
        event.add('summary', meeting.title)
        event.add('dtstart', tz.localize(meeting.start_time))
        event.add('dtend', tz.localize(meeting.end_time))
        event.add('description',
                  u'Møte generert av %s. Antall deltakere: %s. ' % (app.config['APP_NAME'],
                                                                    meeting.participant_count))
        cal.add_component(event)

    export = StringIO.StringIO()
    export.writelines(cal.to_ical())
    export.seek(0)
    return send_file(export,
                     attachment_filename=filename + '.ics',
                     as_attachment=True)
def home():
    """ Renders the home page """
    # Meeting list will be shown at the bottom of the page
    meeting_list = Meeting.get_user_meetings(current_user.id)
    # Selected world (in meeting tab) defaults to None and gets overridden if there is a world selected
    world = None
    # Default to world selection tab
    # 0 is world selection tab and 1 is meeting details tab
    set_tab = 0
    # Locale encoding used for day names
    # preferred_encoding = locale.getpreferredencoding()
    preferred_encoding = 'UTF-8'

    # A form is posted
    if request.method == 'POST':
        # If request is a redirect from map page, we will have a WorldForm
        world_form = forms.WorldForm(request.form)
        if world_form.validate():
            # Go to meeting details tab
            set_tab = 1
            # Show empty meeting form
            meeting_form = forms.MeetingForm()
            try:
                world_id = int(world_form.world_id.data)
                description = world_form.description.data
                world = World.get_by_id(world_id)
                if world:
                    # Update description if changed
                    if world.description != description:
                        world.description = description
                        world.store()
                    # Put world ID in meeting form for reference
                    meeting_form.world_id.process_data(str(world_id))
                else:  # World does not exist
                    flash(u'Den valgte Minecraft verdenen eksisterer ikke')
                    set_tab = 0

            except ValueError:
                # A number was not supplied as world ID
                flash(u'world_id ValueError')

            return render_template(
                'index.html',
                set_tab=set_tab,
                title=u'Hjem',
                meetings=meeting_list,
                form=meeting_form,
                world=world,
                action=url_for('home'),
                locale=preferred_encoding
            )

        # Check if a meeting form is posted
        form = forms.MeetingForm(request.form)
        if form.validate():
            # If valid, put data from form into Meeting object
            meeting = Meeting(user_id=current_user.id)
            form.populate_obj(meeting)
            if meeting.world_id:  # World ID will be none if the posted value is not an integer
                if World.exists(meeting.world_id):  # Check that the world exists in the database
                    meeting.store()

                    # Celery stuff
                    # tasks.meeting_test.apply_async()
                    tasks.meeting_test.apply_async(eta=meeting.start_time, expires=meeting.end_time)

                    flash(u'Nytt møte lagt til')
                    return redirect(url_for('home'))

                else:  # World does not exist
                    flash(u'Den valgte Minecraft verdenen eksisterer ikke')
                    set_tab = 1

            else:  # World probably not chosen
                flash(u'Ingen Minecraft verden valgt')
                set_tab = 0

        else:  # Form not valid
            flash(u'Feil i skjema!')
            set_tab = 1
            try:  # Insert world info
                world_id = int(form.world_id.data)
                world = World.get_by_id(world_id)
            except ValueError:
                pass

    else:  # If not POST
        # Serve blank form
        form = forms.MeetingForm()

    return render_template(
        'index.html',
        set_tab=set_tab,
        title=u'Hjem',
        meetings=meeting_list,
        form=form,
        world=world,
        action=url_for('home'),
        locale=preferred_encoding
    )