#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

__author__ = 'RemiZOffAlex'
__copyright__ = '(c) RemiZOffAlex'
__license__ = 'MIT'
__email__ = 'remizoffalex@mail.ru'

import re

class BogonIP:
    def __contains__(self, IP):
        result = False
        patterns = [
            "192\.168\.\d{1,3}\.\d{1,3}",
            "10\.\d{1,3}\.\d{1,3}\.\d{1,3}",
            "172\.16\.\d{1,3}\.\d{1,3}",
            "127\.\d{1,3}\.\d{1,3}\.\d{1,3}"
        ]
        for pattern in patterns:
                match = re.search(pattern, IP)
                if match:
                        result = True
        return result

class IPList:
    def __init__(self, ips=[]):
        self.iplist = []
        self.iterator = iter(self.iplist)
        for ip in ips:
            self += ip

    def __iter__(self):
        """
        Инициализация итератора
        """
        self.iterator = iter(self.iplist)
        return self.iterator

    def __len__(self):
        """
        Вернуть длину списка
        """
        return len(self.iplist)

    def next(self):
        """
        Выборка элемента
        """
        result = self.iterator.next()
        return result

    def __add__(self, IP):
        """
        Добавить IP в БД
        """
        if IP not in self:
            self.Insert(IP)
        return self

    def Insert(self, IP):
        """
        Вставка в отсортированный массив
        """
        min, max = 0, len(self.iplist)
        while max - min > 0:
            m = (min + max) // 2 # Делим отрезок пополам
            if self.iplist[m] > IP:
                max = m
            else:
                min = m + 1
        result = self.iplist[:max] + [IP] + self.iplist[max:]
        self.iplist = result

    def Delete(self, IP):
        """
        Удаление из массива
        """
        if IP in self:
            self.iplist.remove(IP)

    def __contains__(self, IP):
        """
        Бинарный поиск
        """
        i = 0
        j = len(self.iplist)-1
        if j == -1:
            return False
        while i < j:
            m = int((i+j)/2)
            if IP > self.iplist[m]:
                i = m+1
            else:
                j = m
        #тут не важно j или i
        if self.iplist[j] == IP:
            return True
        else:
            return False

    def Search(self, IP):
        """
        Бинарный поиск
        """
        i = 0
        j = len(self.iplist)-1
        if j == -1:
            return None
        while i < j:
            m = int((i+j)/2)
            if IP > self.iplist[m]:
                i = m+1
            else:
                j = m
        #тут не важно j или i
        if self.iplist[j] == IP:
            return self.iplist[j]
        else:
            return None
