import json
import os
from collections import namedtuple
from copy import deepcopy

from corehq.apps.callcenter.utils import get_call_center_domains

MODULE_PATH = os.path.dirname(__file__)
DATA_SOURCES_PATH = os.path.join(MODULE_PATH, 'data_sources')
FORM_DATA_SOURCE_PATH = os.path.join(DATA_SOURCES_PATH, 'call_center_forms.json')
CASE_DATA_SOURCE_PATH = os.path.join(DATA_SOURCES_PATH, 'call_center_cases.json')
CASE_ACTION_DATA_SOURCE_PATH = os.path.join(DATA_SOURCES_PATH, 'call_center_case_actions.json')

CallCenterReportDataSources = namedtuple('CallCenterReportDataSources', 'forms, cases, case_actions')


def call_center_data_source_provider():
    call_center_data_sources = get_data_source_templates()

    for domain in get_call_center_domains():
        if domain.use_fixtures:
            for data_source_json in call_center_data_sources:
                yield _make_data_source_for_domain(data_source_json, domain)


def get_data_source_templates():
    call_center_data_sources = [
        _get_json(FORM_DATA_SOURCE_PATH),
        _get_json(CASE_DATA_SOURCE_PATH),
        _get_json(CASE_ACTION_DATA_SOURCE_PATH),
    ]
    return call_center_data_sources


def get_sql_adapters_for_domain(domain):
    forms, cases, case_actions = get_data_source_templates()
    return CallCenterReportDataSources(
        forms=_get_sql_adapter(domain, forms),
        cases=_get_sql_adapter(domain, cases),
        case_actions=_get_sql_adapter(domain, case_actions),
    )


def _get_sql_adapter(domain, data_source_json):
    from corehq.apps.userreports.sql import IndicatorSqlAdapter
    data_source = _make_data_source_for_domain(data_source_json, domain)
    return IndicatorSqlAdapter(data_source)


def _make_data_source_for_domain(data_source_json, domain_lite):
    from corehq.apps.userreports.models import StaticDataSourceConfiguration
    from corehq.apps.userreports.models import DataSourceConfiguration

    doc = deepcopy(data_source_json)
    doc['domain'] = domain_lite.name
    doc['_id'] = StaticDataSourceConfiguration.get_doc_id(domain_lite.name, doc['table_id'])
    return DataSourceConfiguration.wrap(doc)


def _get_json(path):
    with open(path) as f:
        return json.load(f)

@@ -924,16 +924,21 @@
 , domain
+.name
 )%0A%0A%0Adef 
@@ -1214,16 +1214,21 @@
 n(domain
+_name
 ):%0A    f
@@ -1360,16 +1360,21 @@
 r(domain
+_name
 , forms)
@@ -1408,24 +1408,29 @@
 apter(domain
+_name
 , cases),%0A  
@@ -1471,16 +1471,21 @@
 r(domain
+_name
 , case_a
@@ -1528,16 +1528,21 @@
 r(domain
+_name
 , data_s
@@ -1689,16 +1689,21 @@
 , domain
+_name
 )%0A    re
@@ -1800,19 +1800,19 @@
  domain_
-lit
+nam
 e):%0A    
@@ -2016,29 +2016,24 @@
 '%5D = domain_
-lite.
 name%0A    doc
@@ -2094,13 +2094,8 @@
 ain_
-lite.
 name

rename variables for clarity and only pass in domain name