# -*- coding: utf-8 -*-
import logging
from os.path import dirname, join
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib


logger = logging.getLogger(__name__)


def get_ta_version():
    with open(join(dirname(dirname(__file__)), 'requirements.txt')) as fd:
        reqs = fd.read().split('\n')

    return u'Версия сборки Техноаудита: {}'.format(reqs[1])


def proceed_form_value(value, def_value=None):
    if value in [None, 'None', '']:
        if def_value:
            return def_value
        else:
            return None
    else:
        return value


def get_cs_src(task):
    try:
        last_date = [comment for comment in task.issue.comments if u'Задача в работе.' in comment.text and
                     comment.createdBy.login == 'robot-keywords'].pop().createdAt
    except IndexError:
        return []
    except Exception as exc:
        logger.exception('%s: Oops!')
        raise exc

    src_comments = [comment.text for comment in task.issue.comments if u'Highlight result' in comment.text and
                    comment.createdBy.login == 'robot-keywords' and
                    comment.createdAt > last_date]

    return [get_url_and_name(com) for com in src_comments]


def get_url_and_name(comment):
    url = comment[comment.find('((') + 2:]
    src_name = url

    url = url[:url.find(' ')]
    src_name = src_name.replace(url, '').replace('))', '').strip()
    return url, src_name


def normalize_login(login):

    return login.strip().lower().replace('.', '-')


def get_src_cur(src):
    return src.replace('.tar.gz', '').split('_')[2]


def send_mail(from_, password, subject, message, to):
    msg = MIMEMultipart('alternative')
    text = MIMEText(message, 'html', 'utf8')

    msg['Subject'] = subject
    msg['From'] = from_
    msg['To'] = ', '.join(to)
    msg.attach(text)

    conn = smtplib.SMTP_SSL('smtp.yandex-team.ru', 465)
    conn.set_debuglevel(False)
    conn.login(from_, password)

    try:
        conn.sendmail(from_, to, msg.as_string())
    finally:
        conn.close()
