from datetime import datetime

from django.db import models
from simple_history.models import HistoricalRecords


def user_directory_path(instance, filename):
    timestr = str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))
    new_filename = filename.split(".")
    return 'platform/{0}_{1}.{2}'.format(
        instance.id, timestr, new_filename[len(new_filename) - 1]
    )


class Platform(models.Model):
    class Status(models.TextChoices):
        ACTIVE = 'ACTIVE'
        INACTIVE = 'INACTIVE'
        UNAVAILABLE = 'UNAVAILABLE'
        HIDE_REVIEWS = 'HIDE_REVIEWS'

    name = models.CharField(max_length=100, blank=True)
    logo = models.ImageField(
        upload_to=user_directory_path, null=True, blank=True, max_length=500
    )
    is_popular = models.BooleanField(default=False)
    url = models.CharField(unique=True, max_length=500)
    example_url = models.CharField(blank=True, max_length=500)
    status = models.CharField(
        max_length=50,
        choices=Status.choices,
        default=Status.ACTIVE,
        db_index=True,
    )
    display_order = models.IntegerField(
        blank=True,
        null=True,
        default=None,
    )

    class Meta:
        ordering = ['display_order', 'name']


class ReviewSource(models.Model):
    class SyncStatus(models.TextChoices):
        NOT_SYNC = 'NOT_SYNC'
        SYNCING = 'SYNCING'
        SYNCED = 'SYNCED'
        FALSE = 'FALSE'

    platform = models.ForeignKey(
        Platform,
        related_name='review_sources',
        on_delete=models.CASCADE,
    )
    company = models.ForeignKey(
        'companies.Company',
        related_name='review_sources',
        on_delete=models.CASCADE,
    )
    url = models.CharField(max_length=500)
    reviews_count = models.IntegerField(blank=True, null=True, default=None)
    average_rating = models.FloatField(blank=True, null=True, default=None)
    history = HistoricalRecords()
    sync_status = models.CharField(
        choices=SyncStatus.choices,
        max_length=30,
        default=SyncStatus.NOT_SYNC,
        null=True,
        blank=True,
    )
    other = models.JSONField(blank=True, null=True)
    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['company', 'platform'], name='unique_company_platform'
            )
        ]
