# -*- coding: utf-8 -*-
import hashlib

from django.conf import settings
from django.utils import timezone
from django.utils.deconstruct import deconstructible

from events.common_app.utils import url_join
from events.common_storages.models import ProxyStorageModel
from events.common_storages.storage import MdsStorage


@deconstructible
class ProxyStorage(MdsStorage):
    def url(self, name, site_type='internal'):
        domain = settings.DEFAULT_FRONTEND_DOMAIN
        path = settings.FILE_PATH_PREFIX
        return url_join(f'https://{domain}{path}', '/files/', path=name)

    def get_sha256_of_content(self, name, content):
        content.seek(0)
        m = hashlib.sha256()
        while True:
            buf = content.read(4096)
            if not buf:
                break
            if isinstance(buf, str):
                buf = buf.encode()
            m.update(buf)
        content.seek(0)
        m.update(name.encode())
        return m.hexdigest()

    def save(self, name, content, max_length=255, user_id=None, survey_id=None):
        path = super().save(name, content)
        file_meta_info = ProxyStorageModel(
            path=f'/{path}',
            original_name=content.name[:max_length],
            date_created=timezone.now(),
            sha256=self.get_sha256_of_content(name, content),
            namespace=settings.MDS_NAMESPACE,
            user_id=user_id,
            survey_id=survey_id,
        )
        if hasattr(content, 'size'):
            file_meta_info.file_size = content.size
        file_meta_info.save()
        return file_meta_info.path
