# -*- coding: utf-8 -*-
__author__ = 'SDE'

import urllib3
import json

def send_SMS(phone, text, urgent=False, staff=False):
    import re
    from BaseModels.mailSender import techSendMail
    print('send_SMS')

    # change all + for GET request
    text = text.replace(' ', '+')
    text = text.encode('utf-8')

    if not staff:
        phone = phone.replace(' ', '')
        p = re.compile('\d{7,12}')
        phone_list = p.findall(phone)

        if not phone_list:
            return u'phone DoesNotExist'

        phone = phone_list[0]

    phone.encode('utf-8')

    http_request = 'http://cp.websms.by/?r=api/msg_send' \
              '&user=administrator@baldenini.by' \
              '&apikey=zTwevODOYl' \
              '&sender=Baldenini'
              # '&test=1'

    if urgent:
        http_request = http_request + '&urgent=1'
    http_request = http_request + '&recipients=' + phone

    http_request = http_request.encode('utf-8')

    http_request = http_request + '&message=' + text

    http = urllib3.PoolManager()

    r = http.request('GET', http_request)

    r_status = json.loads(r.data)

    if r_status['status'] == 'error':
        message = r_status['message']
        try:
            req = http_request.decode('utf-8')
            message = req + u'<br>' + message
            # message = message.decode('utf-8')
            techSendMail(message)
        except:
            pass
    else:
        message = None

    stat = {
        'status' : r_status,
        'message' : message,
    }

    print('sms_status', phone, stat)

    return r_status
    # return u'Accept'