def create_rule_by_blocks(self, blocks, filter_applied, new_block):
        # filter_applied = filter_applied.replace('\n', '')
        # Identifier block in rule_applied and the block to be inserted
        new_blocks_rule = list()
        has_block_in_filter = False
        if clear_newline_chr(
                new_block.content) in clear_newline_chr(filter_applied):
            raise VipRequestBlockAlreadyInRule(None,
                                               'Block is already in rule')
        for block_env in blocks:
            if clear_newline_chr(
                    block_env.content) in clear_newline_chr(filter_applied):
                new_blocks_rule.append(
                    self.create_rule_content_dict(block_env.id,
                                                  block_env.content))
                has_block_in_filter = True
            elif clear_newline_chr(block_env.content) == clear_newline_chr(
                    new_block.content):
                new_blocks_rule.append(
                    self.create_rule_content_dict(block_env.id,
                                                  block_env.content))

        if not has_block_in_filter:
            return list(), False

        # Create new rule with your contents
        new_rule_content = list()
        after_index_to_insert_new_rule_content = ''
        after_index_to_insert_old_rule_content = ''
        for i in range(len(new_blocks_rule)):
            # If the block is in rule applied
            if clear_newline_chr(
                    new_blocks_rule[i]['content']) in clear_newline_chr(
                        filter_applied):
                # position of block in filter_applied
                index = filter_applied.index(new_blocks_rule[i]['content'])
                # First block found
                if i == 0:
                    if index == 0:
                        # Do nothing here, it is the first content
                        pass
                    else:
                        # Get all content before it and make a rule content
                        new_rule_content.insert(
                            0,
                            self.create_rule_content_dict(
                                0, filter_applied[0:index]))
                    # Than append the block
                    new_rule_content.append(
                        self.create_rule_content_dict(
                            new_blocks_rule[i]['content_block_id'],
                            new_blocks_rule[i]['content']))
                    # Saves the index to insert the new block after this
                    # content
                    after_index_to_insert_new_rule_content = len(
                        new_rule_content)
                # Last block found
                elif i == (len(new_blocks_rule) - 1):
                    if after_index_to_insert_old_rule_content:
                        # Index to insert the block that already was in
                        # filter_applied after the new block
                        new_rule_content.insert(
                            after_index_to_insert_old_rule_content,
                            self.create_rule_content_dict(
                                new_blocks_rule[i]['content_block_id'],
                                new_blocks_rule[i]['content']))
                    else:
                        # None new block was inserted, just append the block
                        # that already exists
                        new_rule_content.append(
                            self.create_rule_content_dict(
                                new_blocks_rule[i]['content_block_id'],
                                new_blocks_rule[i]['content']))
                    if index + len(new_blocks_rule[i]['content']) == len(
                            filter_applied):
                        # Do nothing, it is the last content
                        pass
                    else:
                        # Get all content after it and make a rule content
                        new_rule_content.append(
                            self.create_rule_content_dict(
                                0, filter_applied[
                                    index + len(new_blocks_rule[i]['content']
                                                ):len(filter_applied)]))
                else:
                    # Than append the block
                    new_rule_content.append(
                        self.create_rule_content_dict(
                            new_blocks_rule[i]['content_block_id'],
                            new_blocks_rule[i]['content']))
                    # Saves the index to insert the new block after this
                    # content
                    after_index_to_insert_new_rule_content = len(
                        new_rule_content)
                    after_index_to_insert_old_rule_content = len(
                        new_rule_content)

            else:
                # if a block was inserted before, then it has the index to
                # insert after
                if after_index_to_insert_new_rule_content:
                    # Insert new block after the last block found
                    new_rule_content.insert(
                        after_index_to_insert_new_rule_content,
                        self.create_rule_content_dict(
                            new_blocks_rule[i]['content_block_id'],
                            new_blocks_rule[i]['content']))
                    # if isn't the last block
                    if i != (len(new_blocks_rule) - 1):
                        # Get all content after the last block and before the
                        # next content block make a rule content
                        start = filter_applied.index(new_rule_content[
                            after_index_to_insert_new_rule_content -
                            1]['content']) + len(new_rule_content[
                                after_index_to_insert_new_rule_content -
                                1]['content'])
                        end = filter_applied.index(
                            new_blocks_rule[i + 1]['content'])
                        content = filter_applied[start:end]
                        if content.strip():
                            new_rule_content.append(
                                self.create_rule_content_dict(0, content))
                    else:
                        # Get all content after the last block and make a rule
                        # content
                        start = filter_applied.index(new_rule_content[
                            after_index_to_insert_new_rule_content -
                            1]['content']) + len(new_rule_content[
                                after_index_to_insert_new_rule_content -
                                1]['content'])
                        end = len(filter_applied)
                        new_rule_content.append(
                            self.create_rule_content_dict(
                                0, filter_applied[start:end]))
                else:
                    # if isnt the last block
                    if i != (len(new_blocks_rule) - 1):
                        # Insert new block before the first block found
                        new_rule_content.insert(
                            0,
                            self.create_rule_content_dict(
                                0, filter_applied[0:filter_applied.index(
                                    new_blocks_rule[i + 1]['content'])]))
                        new_rule_content.append(
                            self.create_rule_content_dict(
                                new_blocks_rule[i]['content_block_id'],
                                new_blocks_rule[i]['content']))
                        # Index to insert the rule content thas already exists
                        # in rule_applied
                        after_index_to_insert_old_rule_content = len(
                            new_rule_content)

        return new_rule_content, True
    def create_rule_by_blocks(self, blocks, filter_applied, new_block):
        # filter_applied = filter_applied.replace('\n', '')
        # Identifier block in rule_applied and the block to be inserted
        new_blocks_rule = list()
        has_block_in_filter = False
        if clear_newline_chr(new_block.content) in clear_newline_chr(filter_applied):
            raise VipRequestBlockAlreadyInRule(
                None, 'Block is already in rule')
        for block_env in blocks:
            if clear_newline_chr(block_env.content) in clear_newline_chr(filter_applied):
                new_blocks_rule.append(
                    self.create_rule_content_dict(block_env.id, block_env.content))
                has_block_in_filter = True
            elif clear_newline_chr(block_env.content) == clear_newline_chr(new_block.content):
                new_blocks_rule.append(
                    self.create_rule_content_dict(block_env.id, block_env.content))

        if not has_block_in_filter:
            return list(), False

        # Create new rule with your contents
        new_rule_content = list()
        after_index_to_insert_new_rule_content = ''
        after_index_to_insert_old_rule_content = ''
        for i in range(len(new_blocks_rule)):
            # If the block is in rule applied
            if clear_newline_chr(new_blocks_rule[i]['content']) in clear_newline_chr(filter_applied):
                # position of block in filter_applied
                index = filter_applied.index(new_blocks_rule[i]['content'])
                # First block found
                if i == 0:
                    if index == 0:
                        # Do nothing here, it is the first content
                        pass
                    else:
                        # Get all content before it and make a rule content
                        new_rule_content.insert(
                            0, self.create_rule_content_dict(0, filter_applied[0:index]))
                    # Than append the block
                    new_rule_content.append(self.create_rule_content_dict(
                        new_blocks_rule[i]['content_block_id'], new_blocks_rule[i]['content']))
                    # Saves the index to insert the new block after this
                    # content
                    after_index_to_insert_new_rule_content = len(
                        new_rule_content)
                # Last block found
                elif i == (len(new_blocks_rule) - 1):
                    if after_index_to_insert_old_rule_content:
                        # Index to insert the block that already was in
                        # filter_applied after the new block
                        new_rule_content.insert(after_index_to_insert_old_rule_content, self.create_rule_content_dict(
                            new_blocks_rule[i]['content_block_id'], new_blocks_rule[i]['content']))
                    else:
                        # None new block was inserted, just append the block
                        # that already exists
                        new_rule_content.append(self.create_rule_content_dict(
                            new_blocks_rule[i]['content_block_id'], new_blocks_rule[i]['content']))
                    if index + len(new_blocks_rule[i]['content']) == len(filter_applied):
                        # Do nothing, it is the last content
                        pass
                    else:
                        # Get all content after it and make a rule content
                        new_rule_content.append(self.create_rule_content_dict(
                            0, filter_applied[index + len(new_blocks_rule[i]['content']):len(filter_applied)]))
                else:
                    # Than append the block
                    new_rule_content.append(self.create_rule_content_dict(
                        new_blocks_rule[i]['content_block_id'], new_blocks_rule[i]['content']))
                    # Saves the index to insert the new block after this
                    # content
                    after_index_to_insert_new_rule_content = len(
                        new_rule_content)
                    after_index_to_insert_old_rule_content = len(
                        new_rule_content)

            else:
                # if a block was inserted before, then it has the index to
                # insert after
                if after_index_to_insert_new_rule_content:
                    # Insert new block after the last block found
                    new_rule_content.insert(after_index_to_insert_new_rule_content, self.create_rule_content_dict(
                        new_blocks_rule[i]['content_block_id'], new_blocks_rule[i]['content']))
                    # if isn't the last block
                    if i != (len(new_blocks_rule) - 1):
                        # Get all content after the last block and before the
                        # next content block make a rule content
                        start = filter_applied.index(new_rule_content[after_index_to_insert_new_rule_content - 1][
                                                     'content']) + len(new_rule_content[after_index_to_insert_new_rule_content - 1]['content'])
                        end = filter_applied.index(
                            new_blocks_rule[i + 1]['content'])
                        content = filter_applied[start:end]
                        if content.strip():
                            new_rule_content.append(
                                self.create_rule_content_dict(0, content))
                    else:
                        # Get all content after the last block and make a rule
                        # content
                        start = filter_applied.index(new_rule_content[after_index_to_insert_new_rule_content - 1][
                                                     'content']) + len(new_rule_content[after_index_to_insert_new_rule_content - 1]['content'])
                        end = len(filter_applied)
                        new_rule_content.append(
                            self.create_rule_content_dict(0, filter_applied[start:end]))
                else:
                    # if isnt the last block
                    if i != (len(new_blocks_rule) - 1):
                        # Insert new block before the first block found
                        new_rule_content.insert(0, self.create_rule_content_dict(
                            0, filter_applied[0:filter_applied.index(new_blocks_rule[i + 1]['content'])]))
                        new_rule_content.append(self.create_rule_content_dict(
                            new_blocks_rule[i]['content_block_id'], new_blocks_rule[i]['content']))
                        # Index to insert the rule content thas already exists
                        # in rule_applied
                        after_index_to_insert_old_rule_content = len(
                            new_rule_content)

        return new_rule_content, True
    def insert_block_in_rule(self, id_block, rule_applied):
        """
        Insert the specified block in rule.

        @param id_block: Block Identifier to insert.
        @param rule_applied: Rule already appliad in Vip.

        @return: List of dicts with following structure: [{'content_block_id': <block_id>, 'content': <block_content>}].

        @raise VipRequestNoBlockInRule: Rule don't have any block associated.
        @raise VipRequestBlockAlreadyInRule: Block is already in rule.
        """
        block_in_rules = list()
        for content_rule in rule_applied.rulecontent_set.all():

            blocks_envs = BlockRules.objects.filter(
                environment=content_rule.rule.environment)

            is_add = False
            for b in blocks_envs:
                if clear_newline_chr(b.content) == clear_newline_chr(
                        content_rule.content):
                    block_in_rules.append({
                        'content_block_id': b.id,
                        'content': content_rule.content
                    })
                    is_add = True
                    break

            if not is_add:
                block_in_rules.append({
                    'content_block_id': 0,
                    'content': content_rule.content
                })
            # try:
            # content_block = BlockRules.objects.get(content=content_rule.
            # content, environment=content_rule.rule.environment)
            # content_block_id = content_block.id
            # except Exception:
            # Isn't a block, is a custom content
            # pass
            # finally:
            # block_in_rules.append({'content_block_id': content_block_id,
            # 'content': content_rule.content})
        block = BlockRules.objects.get(pk=id_block,
                                       environment=rule_applied.environment)

        before_block_index = ''
        after_block_index = ''
        for i in range(len(block_in_rules)):
            content_block_id = block_in_rules[i]['content_block_id']

            if block.id == content_block_id:
                raise VipRequestBlockAlreadyInRule(None,
                                                   'Block is already in rule')

            if content_block_id != 0:
                # is a block, not a custom content
                if block.id > content_block_id:
                    before_block_index = i
                elif block.id < content_block_id and after_block_index == '':
                    after_block_index = i

        index_to_insert = None

        if before_block_index != '':
            # first block before the new block
            index_to_insert = before_block_index + 1
        elif after_block_index != '':
            # first block after the new block
            index_to_insert = after_block_index

        if index_to_insert is None:
            raise VipRequestNoBlockInRule(
                None, "Rule don't have any block associated.")

        # list.insert(index, object) -- insert object before index
        block_in_rules.insert(index_to_insert, {
            'content_block_id': block.id,
            'content': block.content
        })

        return block_in_rules
    def insert_block_in_rule(self, id_block, rule_applied):
        """
        Insert the specified block in rule.

        @param id_block: Block Identifier to insert.
        @param rule_applied: Rule already appliad in Vip.

        @return: List of dicts with following structure: [{'content_block_id': <block_id>, 'content': <block_content>}].

        @raise VipRequestNoBlockInRule: Rule don't have any block associated.
        @raise VipRequestBlockAlreadyInRule: Block is already in rule.
        """
        block_in_rules = list()
        for content_rule in rule_applied.rulecontent_set.all():

            blocks_envs = BlockRules.objects.filter(
                environment=content_rule.rule.environment)

            is_add = False
            for b in blocks_envs:
                if clear_newline_chr(b.content) == clear_newline_chr(content_rule.content):
                    block_in_rules.append({
                        'content_block_id': b.id,
                        'content': content_rule.content})
                    is_add = True
                    break

            if not is_add:
                block_in_rules.append(
                    {'content_block_id': 0, 'content': content_rule.content})
            # try:
                # content_block = BlockRules.objects.get(content=content_rule.
                # content, environment=content_rule.rule.environment)
                # content_block_id = content_block.id
            # except Exception:
                # Isn't a block, is a custom content
                # pass
            # finally:
                # block_in_rules.append({'content_block_id': content_block_id,
                # 'content': content_rule.content})
        block = BlockRules.objects.get(
            pk=id_block, environment=rule_applied.environment)

        before_block_index = ''
        after_block_index = ''
        for i in range(len(block_in_rules)):
            content_block_id = block_in_rules[i]['content_block_id']

            if block.id == content_block_id:
                raise VipRequestBlockAlreadyInRule(
                    None, 'Block is already in rule')

            if content_block_id != 0:
                # is a block, not a custom content
                if block.id > content_block_id:
                    before_block_index = i
                elif block.id < content_block_id and after_block_index == '':
                    after_block_index = i

        index_to_insert = None

        if before_block_index != '':
            # first block before the new block
            index_to_insert = before_block_index + 1
        elif after_block_index != '':
            # first block after the new block
            index_to_insert = after_block_index

        if index_to_insert is None:
            raise VipRequestNoBlockInRule(
                None, "Rule don't have any block associated.")

        # list.insert(index, object) -- insert object before index
        block_in_rules.insert(
            index_to_insert, {'content_block_id': block.id, 'content': block.content})

        return block_in_rules