import csv
import os

from django.conf import settings
from django.apps import apps

from intranet.search.core.sources.mldescription.utils import get_ml_name
from intranet.search.core.utils import http
from intranet.search.core.tvm import tvm2_client

# ml рассылки должны индексироваться первыми
__all__ = ['ml', 'separator', 'yamoney']


def ml():
    """ Возвращает список рассылок ml
    """
    endpoint = settings.ISEARCH['api']['ml']['list_info']

    url = endpoint.url(query={'fields': 'name,email,is_open,info,exchange_name'})
    headers = endpoint.headers()
    headers[settings.TVM2_SERVICE_HEADER] = tvm2_client.get_service_ticket('mldescription')

    response = http.call_with_retry(http.create_session().get, url,
                                    timeout=20, headers=headers,
                                    verify=settings.ISEARCH_CA_CERTS)

    for data in response.json()['maillists']:
        data['email_type'] = 'ml'
        data['exchange'] = data.pop('exchange_name', None)
        data['url'] = 'http://ml.yandex-team.ru/lists/%s/' % data['name']
        yield data


def separator():
    """ Возвращает список рассылок сепаратора
    """
    url = settings.ISEARCH['api']['separator']['mail_list'].url()
    response = http.call_with_retry(http.create_session().get, url)
    for email in response.json():
        yield {'email': email, 'name': get_ml_name(email), 'email_type': 'separator'}


def yamoney():
    """ Возвращает список рассылок яндекс денег
    """
    path = os.path.join(apps.get_app_config('isearch').path, 'fixtures/yamoney-list-default.csv')
    with open(path) as f:
        for row in csv.reader(f):
            email = row[0]
            yield {'email': email, 'name': get_ml_name(email), 'email_type': 'yamoney'}
