# -*- coding: utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from os.path import dirname, join
import pandas as pd
import requests
import smtplib
from textwrap import dedent
from io import StringIO
import logging
from yt import wrapper as yt
from data_worker import SECRET

logger = logging.getLogger(__name__)


def send_mail(subject, message, from_='%s@yandex-team.ru' % SECRET['passport']['login'],
              password=SECRET['passport']['password'], to=('leroy@yandex-team.ru', )):
    pass
    # try:
    #     msg = MIMEMultipart('alternative')
    #     text = MIMEText(message, 'html', 'utf8')
    #
    #     msg['From'] = from_
    #     msg['To'] = ', '.join(to)
    #     msg['Subject'] = subject
    #     msg.attach(text)
    #
    #     conn = smtplib.SMTP_SSL('smtp.yandex-team.ru', 465)
    #     conn.set_debuglevel(False)
    #     conn.login(from_, password)
    #
    #     conn.sendmail(from_, to, msg.as_string())
    #     conn.close()
    #
    # except:
    #     logger.exception('Oops!')


def write_table(target_path, schema, df):
    data = df.to_dict('records')
    yt_client = yt.YtClient(token=SECRET['token'], proxy='hahn')
    with yt_client.Transaction():
        if yt_client.exists(target_path):
            yt_client.remove(target_path)

        yt_client.write_table(yt_client.TablePath(target_path, schema=schema), data)

    logger.info(target_path)


def read_table(table_path, columns):
    yt_client = yt.YtClient(token=SECRET['token'], proxy='hahn')
    table = yt_client.read_table(
        table_path,
        raw=True,
        format=yt.SchemafulDsvFormat(columns=columns,
                                     attributes={'missing_value_mode': 'print_sentinel',
                                                 'missing_value_sentinel': 'null'})
    )
    df = pd.read_table(
        StringIO('\n'.join(table).decode('utf-8')),
        names=columns,
        encoding='utf-8', decimal='.', na_values=('Null', 'null', 'NULL'), na_filter=True,
        quoting=3, low_memory=True, engine='c'
    )

    return df


def get_query_text(query_name):
    with open(join(dirname(__file__), 'queries', '%s.sql' % query_name)) as fd:
        return dedent(fd.read().decode('utf8')).strip()


def read_query_from_arc():
    for i in range(4):
        query = requests.get(
            url='https://a.yandex-team.ru/api/tree/blob/trunk/arcadia/junk/i-anokhin/weekly_update.sql',
            headers={'Authorization': 'OAuth %s' % SECRET['token']}, verify=False).content.decode('utf-8')
        if query not in [None, '']:
            return query
