"""
Created on Jun 18, 2015

@author: noob
"""

from .base import Api
from common.models import PandoraBinary
from common.util.meta import transliterate
from common.util.clients import MDSClient
from datetime import datetime
from django.http import HttpResponseBadRequest, HttpResponse
from django.contrib.auth.models import User
from hashlib import md5
import json
import logging
import time


class AddPandoraBinary(Api):
    http_method_names = ['post']

    @staticmethod
    def post(request):
        login = request.POST.get('login', '')
        try:
            user = User.objects.get(username=login)
            dsc = request.POST.get('dsc', '')
            assert dsc
            data = request.FILES['file']
        except User.DoesNotExist:
            return HttpResponseBadRequest('Unknown login {}'.format(login))
        except AssertionError:
            return HttpResponseBadRequest('Provide description ("dsc")')
        try:
            now = datetime.now()
            uniq = md5(transliterate(dsc) + user.username + str(int(time.mktime(now.timetuple()))))
            uniq = uniq.hexdigest()
            size = data._size
            client = MDSClient()
            resp = client.post(
                uniq,
                data.file,
                size,
            )
            assert resp['success']
            PandoraBinary.objects.create(
                path=resp['url'],
                author=user.username,
                created_at=now,
                last_used=now,
                dsc=dsc,
                size=size,
            )
            return HttpResponse(json.dumps([{'success': True, 'url': resp['url']}]), content_type='application/json')
        except AssertionError:
            return HttpResponse(json.dumps([{'success': False, 'error': resp['error']}]))
        except Exception as exc:
            logging.exception('Could not add pandora_binary due to:')
            return HttpResponse(json.dumps([{'success': False, 'error': exc.__class__.__name__}]),
                                content_type='application/json')
