from tempfile import NamedTemporaryFile
from StringIO import StringIO
from ConfigParser import ConfigParser

from mock import Mock
import yaml

from go.vumitools.routing_table import RoutingTable
from go.vumitools.tests.helpers import djangotest_imports

with djangotest_imports(globals()):
    from django.contrib.auth import authenticate
    from django.core.management.base import CommandError

    from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper
    from go.base.management.commands import go_setup_env


def tmp_yaml_file(lines):
    tmp = NamedTemporaryFile()
    tmp.write('\n'.join(lines))
    tmp.flush()
    return tmp


class FakeFile(StringIO):
    def __enter__(self, *args, **kwargs):
        return self

    def __exit__(self, *args, **kwargs):
        pass


class TestGoSetupEnv(GoDjangoTestCase):

    def setUp(self):
        self.vumi_helper = self.add_helper(DjangoVumiApiHelper())

        self.command = go_setup_env.Command()
        self.command.stdout = StringIO()
        self.command.stderr = StringIO()
        # do whatever setup command.handle() does manually
        self.command.setup_backend(self.vumi_helper.mk_config({}))
        self.add_cleanup(self.command.cleanup)
        self.tagpool = self.command.tagpool
        self.command.file_name_template = 'go_%(file_name)s.%(suffix)s'
        self.command.dest_dir = 'setup_env'
        self.command.config = {
            'redis_manager': {'key_prefix': 'test'},
            'riak_manager': {'bucket_prefix': 'test.'}
        }

        self.command.contact_group_info = []
        self.command.conversation_info = []
        self.command.router_info = []
        self.command.transport_names = []
        self.command.router_names = []
        self.command.application_names = []

        self.tagpool_file = tmp_yaml_file([
            'pools:',
            '  pool1:',
            '    tags: "[\'default%d\' % i for i in range(10)]"',
            '    metadata:',
            '      display_name: "Pool 1"',
            '  pool2:',
            '    tags: ["a", "b", "c"]',
            '    metadata:',
            '      display_name: "Pool 2"',
        ])

        self.workers_file = tmp_yaml_file([
            'transports:',
            '  sms_transport:',
            '    class: vumi.transports.telnet.TelnetServerTransport',
            '    config:',
            '      telnet_port: 8080',
            '  ussd_transport:',
            '    class: vumi.transports.telnet.TelnetServerTransport',
            '    config:',
            '      telnet_port: 8081',
            '',
            'routers:',
            '  keyword:',
            '    class: go.routers.keyword.vumi_app.KeywordRouter',
            '    config:',
            '      redis_manager: {}',
            '      riak_manager: {}',
            '',
            'applications:',
            '  bulk_message:',
            '    class: go.apps.bulk_message.vumi_app.BulkMessageApplication',
            '    config:',
            '      redis_manager: {}',
            '      riak_manager: {}',
        ])

        self.account_1_file = tmp_yaml_file([
            'account:',
            '  email: "user1@go.com"',
            '  password: foo',
            '  first_name: First',
            '  last_name: Last',
            '  applications:',
            '    - go.apps.surveys',
            '    - go.apps.bulk_message',
            '  tagpools:',
            '    - ["pool1", 10]',
            '    - ["pool2", 15]',
            '',
            'channels:',
            '  - "pool1:default0"',
            '  - "pool1:default1"',
            '',
            'conversations:',
            '  - key: "conv1"',
            '    conversation_type: survey',
            '    name: foo',
            '    config:',
            '      foo: bar',
            '  - key: conv2',
            '    conversation_type: wikipedia',
            '    name: Wikipedia',
            '    config: {}',
            '',
            'routers:',
            '  - key: "router1"',
            '    router_type: keyword',
            '    name: foo',
            '    config:',
            '      keyword_endpoint_mapping:',
            '        foo: keyword_foo',
            '',
            'routing_entries:',
            '  - ["conv1", "default", "pool1:default0", "default"]',
            '  - ["pool1:default0", "default", "conv1", "default"]',
            '  - ["router1:INBOUND", "default", "pool1:default1", "default"]',
            '  - ["pool1:default1", "default", "router1:INBOUND", "default"]',
            '  - ["conv2", "default", "router1:OUTBOUND", "default"]',
            '  - ["router1:OUTBOUND", "default", "conv2", "default"]',
            '',
            'contact_groups:',
            '  - key: group1',
            '    name: group1',
            '    contacts_csv: contacts.csv',
        ])

        self.account_2_file = tmp_yaml_file([
            'account:',
            '  email: "user2@go.com"',
            '  password: bar',
            '  applications:',
            '    - go.apps.bulk_message',
            '    - go.apps.jsbox',
            '  tagpools:',
            '    - ["pool1", null]',
            '    - ["pool2", null]',