<%
    mimetype   = config['global']['mimetype']
    charset    = config['global']['charset']
    files      = config['htaccess']['files']
    parent_dir = config['htaccess']['parent_dir']
    end_point  = config['htaccess']['end_point']
    index      = config['htaccess']['index']
    
    allow_files = files['allow']
    
    apis = config['APIs']
    
    api_nokey_array       = [] #has no key
    api_uncacheable_array = [] #not(key1 is int and  0 <= min )
    api_cacheable_array   = [] #not nokey and uncacheable
    api_all_array         = [] #all
    
    
    for api_name in apis:
        api = apis[api_name]
        api_type = api['type']
        if 'cacheable' == api_type:
            api_cacheable_array.append(api_name)
        elif 'uncacheable' == api_type:
            api_uncacheable_array.append(api_name)
        elif 'nokey' == api_type:
            api_nokey_array.append(api_name)
        api_all_array.append(api_name)
        
    api_nokeys   = '|'.join(api_nokey_array)
    api_notcache = '|'.join(api_uncacheable_array)
    api_cache    = '|'.join(api_cacheable_array)
    api_all      = '|'.join(api_all_array)
    
    def get_ep_query(api_name, count):
        ep_query = []
        for i in xrange(1, count + 1):
            ep_query.append('key%s=$%s' % (i, i))
        ep_query = '&'.join(ep_query)
        ep_query = 'apiname=%s&%s' % (api_name, ep_query)
        return ep_query
        
    def str_range(s, n):
        arr = []
        for i in xrange(s, n):
            arr.append(`i`)
        return arr
    
%>\
Options -Indexes +ExecCGI +FollowSymLinks
AddHandler cgi-script .py

order allow,deny
deny from all

#Allow [htaccess - > parent_dir], uses when it had DirectoryIndex request.
<Files ~ "^${ parent_dir }$">
  allow from all
</Files>
#end

#Allow all API in [APIs], uses when it had an API request.
<Files ~ "^(${ api_all })">
  allow from all
</Files>
#end

#Allow [htaccess - > files -> allow].
%for pat in allow_files:
<Files ~ "${ pat }">
  allow from all
</Files>
%endfor
#end


<IfModule mod_rewrite.c>
  RewriteEngine On
%if index:
  
  #Rewrite blank path to [htaccess - > index]. (DirectoryIndex request)
  RewriteRule    ^$    ${ index }
  #end
  
%endif
%if 1 <= len(api_nokey_array):
  
  #[nokey 1]
%for api_name in api_nokey_array:
<%
    api = apis[api_name]
    nokey_index = api['nokey_index']
    key1 = nokey_index[-3]
    key2 = nokey_index[-2]
    key3 = nokey_index[-1]
%>\
  RewriteRule    ^(${ api_name })/$    cache/${ key1 }/${ key2 }/${ key3 }/${ api_name }&${ nokey_index }
%endfor
  #end
  
  #[nokey 2]
  RewriteRule    ^cache  -    "[T=text/html;charset=utf-8]"
  #end
  
  #[nokey 3]
  RewriteCond    %{DOCUMENT_ROOT}%{REQUEST_URI}   !-s
  RewriteRule    ^cache/[^/&]/[^/&]/[^/&]/(${ api_nokeys })&[^/&]+$    ${ end_point }?apiname=$1    [L]
  #end
  
%endif
%if 1 <= len(api_uncacheable_array):
  
  #[uncacheable]
%for api_name in api_uncacheable_array:
<% 
    api = apis[api_name]
    keys = api['keys']
    
    leftPostfix = '([^/&]+)/' * len(keys)
    ep_query = get_ep_query(api_name, len(keys))
%>\
  RewriteRule    ^${ api_name }/${ leftPostfix }$    ${ end_point }?${ ep_query }   [L]
%endfor
  #end
  
%endif
%if 1 <= len(api_cacheable_array):
  
  #[cacheable 1]
  RewriteRule    ^(${ api_cache })/([^/&])/(.*)$         $1/00$2/$3   [N]
  RewriteRule    ^(${ api_cache })/([^/&][^/&])/(.*)$    $1/0$2/$3    [N]
  #end
  
  #[cacheable 2]
%for api_name in api_cacheable_array:
<%
    api = apis[api_name]
    keys = api['keys']
    leftPostfix = '([^/&]+)/' * (len(keys) - 1)
    
    if 1 < len(keys):
        rightPostfix = '&$' + '&$'.join(str_range(5, len(keys) + 4))
    else:
        rightPostfix = ''
%>\
  RewriteRule    ^${ api_name }/([^/&]*([^/&])([^/&])([^/&]))/${ leftPostfix }$    cache/$2/$3/$4/${ api_name }&$1${ rightPostfix }
%endfor
  #end
  
  #[cacheable 3]
  RewriteRule    ^cache  -    "[T=${ mimetype };charset=${ charset }]"
  #end
  
  #[cacheable 4]  
%for api_name in api_cacheable_array:
<%
    api = apis[api_name]
    keys = api['keys']
    
    leftPostfix = '&([^/&]+)' * len(keys)
    ep_query = get_ep_query(api_name, len(keys))
%>\
  RewriteCond    %{DOCUMENT_ROOT}%{REQUEST_URI}   !-s
  RewriteRule    ^cache/[^/&]/[^/&]/[^/&]/${ api_name }${ leftPostfix }$    ${ end_point }?${ ep_query }   [L]
%endfor
  #end
  
%endif
</IfModule>