import re
import yagmail
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
import json

import app_settings

def check_mobile(mobile_number):
    # Mobile numenr starts with 09 and has digits only
    pattern = r"^09\d*"

    if re.match(pattern, mobile_number):
        return True
    else:
        return False
    
def set_mobile(country_code,mobile_number):
    mobile_full = mobile_number
    if len(country_code) > 0:
        mobile_number = mobile_number[1:]
        mobile_full = country_code + mobile_number
    return mobile_full
    
# Convert SQLAlchemy row to JSON
def class2json(data_row):
    d = {}
    for column in data_row.__table__.columns:
        d[column.name] = str(getattr(data_row, column.name))
    return d

# Delete any ID key
def deleteID(inp_json):
    filtered_data = {k: v for k, v in inp_json.items() if ("id" or "ID") not in k}
    return filtered_data


# Setup Customer output data
def customer_output_data(db_json):
    data = db_json
    keys =[]
    values = []
    output_keys = ['address', 'city', 'email', 'first_name', 'last_name', 'location']
    for item in data:
        if item in output_keys:
            value = data.get(item)
            keys.append(item)
            values.append(value)
    
    d = dict(zip(keys,values))
    return d

# Send mail
def send_mail_password(to_email,data):
    try:
        yag = yagmail.SMTP(app_settings.EMAIL_FROM, app_settings.EMAIL_CODE)
        text = str('Nova lozinka:' + str(data))
        yag.send(
        to = to_email,
        subject = 'GetWork - Nova lozinka',
        contents = text
        )
    except Exception as e:
        return False
    return True

def send_mail_payment(to_email,data):
    try:
        yag = yagmail.SMTP(app_settings.EMAIL_FROM, app_settings.EMAIL_CODE)

        name_from = data['name_from']
        name_to = data['name_to']
        service = data['service']
        date = data['date']
        quantity = data['quantity']
        description = data['description']
        if description =="":
            description = "-"
        
        text = f"""Poštovani {name_from},

        Zelimo Vam javiti da je potvrdjena rezervacija za uslugu {service} na dan {date} u trajanju od {quantity} sati.

        Molimo Vas kontaktirajte {name_to} kako bi dogovorili točan termin za izvršenje usluge.
        
        Dodatna poruka za uslugu:
        {description}

        Srdačan pozdrav,
        GetWork tim
        """
        yag.send(
        to = to_email,
        subject = 'GetWork - Rezervacija usluge',
        contents = text
        )
    except Exception as e:
        return False
    return True

def send_mail_order(to_email,data):
    try:
        yag = yagmail.SMTP(app_settings.EMAIL_FROM, app_settings.EMAIL_CODE)

        name_from = data['name_from']
        name_to = data['name_to']
        service = data['service']
        date = data['datetime']
        description = data['description']
        if description =="":
            description = "-"
        
        text = f"""Poštovani {name_from},

        Zelimo Vam javiti da je potvrdjena narudžba za uslugu {service} na dan i sat {date}.

        Molimo Vas kontaktirajte {name_to} kako bi dogovorili točan termin za izvršenje usluge.
        
        Dodatna poruka za uslugu:
        {description}

        Srdačan pozdrav,
        GetWork tim
        """
        yag.send(
        to = to_email,
        subject = 'GetWork - Narudžba usluge',
        contents = text
        )
    except Exception as e:
        return False
    return True



# Location from address
def set_location(address,city):
    geolocator = Nominatim(user_agent="getwork_app_geoloc", timeout=10)

    # Set Country from city
    location = geolocator.geocode(city)
    country = ""

    if location:
        # Reverse for details
        location_details = geolocator.reverse((location.latitude, location.longitude), language="en", zoom=10)
        address_raw = location_details.raw.get("address", {})
        country = address_raw.get("country")

    full_address = f"{address}, {city} " + country
    location = geolocator.geocode(full_address)
    
    res={}
    if location:
        res['Lat'] = location.latitude
        res['Lon'] = location.longitude
    return res

def distance(location1, location2):
    location1 = location1.replace("'", '"')
    location2 = location2.replace("'", '"')
    location1 = json.loads(location1)
    location1['latitude'] = float(location1["Lat"])
    location1['longitude'] = float(location1["Lon"])
    point1=(location1['latitude'],location1['longitude'])
    location2 = json.loads(location2)
    location2['latitude'] = float(location2["Lat"])
    location2['longitude'] = float(location2["Lon"])
    point2=(location2['latitude'],location2['longitude'])
    return geodesic(point1, point2).km

def time_convert(time_decimal):
    hour = int(time_decimal)
    min = int((time_decimal - hour) * 60)
    time_str = f"{hour}"
    if min > 0:
        time_str = f"{hour}:{min:02d}"
    
    return time_str

def service_convert(service_id):
    return app_settings.service_type[int(service_id)]

# OBSOLETE
def price_convert(price_decimal):
    price_str = f"{price_decimal:.2f}" + app_settings.currency['HR']
    return price_str
    
