# Copyright 2014 NeuroData (http://neurodata.io
# Upload Sizes for max memory and number of fields
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import django.http
from django.views.decorators.cache import cache_control
from django.contrib.auth.decorators import login_required
import MySQLdb
import cStringIO
import re

from ndauth.authentication import PublicAuthentication, AnonAllowedAuthentication
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from nduser.models import Token

import webservices.ndwsrest as ndwsrest
import webservices.ndwsprojingest as ndwsprojingest
from webservices.ndwserror import NDWSError, IncorrectSyntaxError
import logging
logger=logging.getLogger("neurodata")


GET_SLICE_SERVICES = ['xy', 'yz', 'xz']
GET_ANNO_SERVICES = ['xyanno', 'yzanno', 'xzanno']
POST_SERVICES = ['hdf5', 'npz', 'raw', 'hdf5_async', 'propagate', 'tiff', 'blosc', 'blaze']

@api_view(['GET','POST'])
@authentication_classes((SessionAuthentication, AnonAllowedAuthentication))
@permission_classes((PublicAuthentication,))
def cutout (request, webargs):
  """Restful URL for all read services to annotation projects"""
  
  try:
    m = re.match(r"(\w+)/(?P<channel>[\w+,-]+)?/?(xy|xz|yz|tiff|hdf5|jpeg|blosc|blaze|npz|raw|zip|id|diff|ids|xyanno|xzanno|yzanno)/([\w\.,/-]*)$", webargs)
    [token, channel, service, cutoutargs] = [i for i in m.groups()]

    if channel is None:
      webargs = '{}/default/{}/{}'.format(token, service, cutoutargs)

  except Exception as e:
    logger.warning("Incorrect format for arguments {}. {}".format(webargs, e))
    raise IncorrectSyntaxError("Incorrect format for arguments {}. {}".format(webargs, e))

  try:
    # GET methods
    if request.method == 'GET':
      if service in GET_SLICE_SERVICES+GET_ANNO_SERVICES:
        return django.http.HttpResponse(ndwsrest.getCutout(webargs), content_type="image/png" )
      elif service in ['hdf5']:
        fname = re.sub ( r',','_', webargs )
        fname = re.sub ( r'/','-', fname )
        response = django.http.HttpResponse(ndwsrest.getCutout(webargs), content_type="product/hdf5" )
        response['Content-Disposition'] = "attachment; filename={}ndcutout.h5".format(fname)
        return response
      elif service in ['blosc', 'diff']:
        fname = re.sub ( r',','_', webargs )
        fname = re.sub ( r'/','-', fname )
        response = django.http.HttpResponse(ndwsrest.getCutout(webargs), content_type="product/blosc" )
        response['Content-Disposition'] = "attachment; filename={}ndcutout.blosc".format(fname)
        return response
      elif service in ['jpeg']: