<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def insert_state_as(target_state_m, state, as_template):
 """ Add a state into a target state In case the state to be insert is a LibraryState it can be chosen to be insert as template. :param rafcon.gui.models.container_state.ContainerStateModel target_state_m: State model of the target state :param rafcon.core.states.State state: State to be insert as template or not :param bool as_template: The flag determines if a handed state of type LibraryState is insert as template :return: """


    if not isinstance(target_state_m, ContainerStateModel) or \
            not isinstance(target_state_m.state, ContainerState):
        logger.error("States can only be inserted in container states")
        return False

    state_m = get_state_model_class_for_state(state)(state)
    if not as_template:
        gui_helper_meta_data.put_default_meta_on_state_m(state_m, target_state_m)

    # If inserted as template, we have to extract the state_copy and respective model
    else:
        assert isinstance(state, LibraryState)
        old_lib_state_m = state_m
        state_m = state_m.state_copy

        previous_state_size = state_m.get_meta_data_editor()['size']
        gui_helper_meta_data.put_default_meta_on_state_m(state_m, target_state_m)
        # TODO check if the not as template case maybe has to be run with the prepare call
        prepare_state_m_for_insert_as(state_m, previous_state_size)

        old_lib_state_m.prepare_destruction(recursive=False)

    # explicit secure that there is no state_id conflict within target state child states
    while state_m.state.state_id in target_state_m.state.states:
        state_m.state.change_state_id()

    target_state_m.expected_future_models.add(state_m)
    target_state_m.state.add_state(state_m.state)

    # secure possible missing models to be generated
    update_models_recursively(state_m, expected=False)