import logging
from collections import namedtuple

from couchdbkit import push, RequestFailed
from couchdbkit.exceptions import ResourceNotFound

log = logging.getLogger(__name__)


def sync_design_docs(db, design_dir, design_name, temp=None, force_index=False):
    """
    pushes design documents and brings new index up to date if temp

    for example it can be used to push new changes to the myapp design doc to
    _design/myapp-tmp

    and then trigger an index of _design/myapp-tmp

    """
    design_name_ = '%s-%s' % (design_name, temp) if temp else design_name
    docid = "_design/%s" % design_name_
    push(design_dir, db, force=True, docid=docid)
    log.info("synced '%s' in couchdb", design_name)
    if temp or force_index:
        # found in the innards of couchdbkit
        view_names = list(db[docid].get('views', {}))
        if view_names:
            log.info('Triggering view rebuild')
            view = '%s/%s' % (design_name_, view_names[0])
            while True:
                try:
                    list(db.view(view, limit=0))
                except RequestFailed as e:
                    if 'timeout' not in e.message:
                        raise
                else:
                    break


def copy_designs(db, design_name, temp='tmp', delete=True):
    log.info("Copy prepared design docs for '%s' in couchdb", design_name)
    tmp_name = '%s-%s' % (design_name, temp)
    from_id = '_design/%s' % tmp_name
    to_id = '_design/%s' % design_name
    try:
        db.copy_doc(from_id, to_id)
        if delete:
            del db[from_id]

    except ResourceNotFound:
        log.warning('%s not found.', from_id)


DesignInfo = namedtuple('DesignInfo', ['db', 'app_label', 'design_path'])

@@ -238,30 +238,11 @@
 None
-, force_index=False
 ):%0A
+
     
@@ -706,29 +706,110 @@
 temp
- or force_index:%0A    
+:%0A        index_design_docs(db, docid, design_name_)%0A%0A%0Adef index_design_docs(db, docid, design_name):%0A
     
@@ -845,20 +845,16 @@
 chdbkit%0A
-    
     view
@@ -895,20 +895,16 @@
 ', %7B%7D))%0A
-    
     if v
@@ -914,20 +914,16 @@
 _names:%0A
-    
         
@@ -966,20 +966,16 @@
         
- 
-   
 view = '
@@ -995,17 +995,16 @@
 ign_name
-_
 , view_n
@@ -1020,20 +1020,16 @@
         
- 
-   
 while Tr
@@ -1044,29 +1044,21 @@
         
- 
-   
 try:%0A
-    
         
@@ -1106,20 +1106,16 @@
         
-  
-  
 except R
@@ -1133,20 +1133,16 @@
 d as e:%0A
-    
         
@@ -1204,22 +1204,14 @@
     
-   
- 
 raise%0A
-    
     
@@ -1224,20 +1224,16 @@
   else:%0A
-    
         

index design doc function