# -*- coding: utf-8 -*-
from django.conf import settings
from django.db import models


class ProxyStorageManager(models.Manager):
    def get_by_sha256(self, sha256, survey_id=None):
        qs = self.model.objects.filter(sha256=sha256)
        if survey_id:
            qs = qs.filter(survey_id=survey_id)
        obj = qs.last()
        if not obj:
            raise self.model.DoesNotExist
        return obj

    def filter_by_path(self, path_list):
        return self.model.objects.filter(path__in=path_list)


class ProxyStorageModel(models.Model):
    path = models.CharField(max_length=255)
    date_created = models.DateTimeField(auto_now_add=True)
    sha256 = models.CharField(max_length=64, null=True, db_index=True)
    file_size = models.BigIntegerField(null=True)
    original_name = models.CharField(max_length=255, null=True)
    namespace = models.CharField(max_length=32, null=True)
    survey = models.ForeignKey('surveyme.Survey', null=True, on_delete=models.SET_NULL)
    user = models.ForeignKey('accounts.User', null=True, on_delete=models.SET_NULL)

    objects = ProxyStorageManager()

    def get_original_storage(self):
        from events.common_storages.proxy_storages import ProxyStorage
        namespace = self.namespace or settings.MDS_OLD_NAMESPACE
        return ProxyStorage(namespace)

    def __str__(self):
        return self.path
