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

import re
import socket
import urllib.request

from thirdparty.socks import socks

def checkProxyFormat(proxy):
    """
    Check proxy format whether like (http|https|socks4|socks5)://address[:port]
    """
    # Check protocol
    prefix = ['http://', 'https://', 'socks4://', 'socks5://']
    for _ in prefix:
        if proxy.startswith(_):
            host = proxy.replace(_, '', 1)

    if 'host' not in locals():
        return False

    # Check host
    return True if re.fullmatch(r'[^:/]+(:[0-9]+)?', host) else False

def updateProxy(proxy):
    protocol, host = proxy.split('://')
    if protocol in ['http', 'https']:
        proxy_support = urllib.request.ProxyHandler({protocol : host})
        opener = urllib.request.build_opener(proxy_support)
        urllib.request.install_opener(opener)
    elif protocol in ['socks4', 'socks5']:
        (address, port) = host.split(':') if ':' in host else (host, '80')
        socks.set_default_proxy(socks.SOCKS4 if protocol == 'socks4' else socks.SOCKS5, address, int(port))
        socket.socket = socks.socksocket
