from django.db import models

# Create your models here.


class LocalBackup(models.Model):
    backup_path = models.CharField(
        max_length=255,
        help_text="Specify the path in the server were the backup files should keep",
    )
    backup_media = models.BooleanField(blank=True, null=True)
    backup_db = models.BooleanField(blank=True, null=True)
    interval = models.BooleanField(blank=True, null=True)
    fixed = models.BooleanField(blank=True, null=True)
    seconds = models.IntegerField(blank=True, null=True)
    hour = models.IntegerField(blank=True, null=True)
    minute = models.IntegerField(blank=True, null=True)
    active = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        # Check if there's an existing instance
        if self.interval == False:
            self.seconds = None
        if self.fixed == False:
            self.hour = None
            self.minute = None
        if LocalBackup.objects.exists():
            # Get the existing instance
            existing_instance = LocalBackup.objects.first()
            # Update the fields of the existing instance with the new data
            for field in self._meta.fields:
                if field.name != "id":  # Avoid changing the primary key
                    setattr(existing_instance, field.name, getattr(self, field.name))
            # Save the updated instance
            super(LocalBackup, existing_instance).save(*args, **kwargs)
            return existing_instance
        else:
            # If no existing instance, proceed with regular save
            super(LocalBackup, self).save(*args, **kwargs)
            return self


class GoogleDriveBackup(models.Model):
    AUTH_METHOD_CHOICES = [
        ('service_account', 'Service Account (Google Workspace only)'),
        ('oauth', 'OAuth 2.0 (Personal & Business accounts)'),
    ]
    
    auth_method = models.CharField(
        max_length=20,
        choices=AUTH_METHOD_CHOICES,
        default='oauth',
        verbose_name="Authentication Method",
        help_text="Choose OAuth for personal Google accounts or Service Account for Google Workspace accounts."
    )
    
    # Service Account fields (for Google Workspace)
    service_account_file = models.FileField(
        upload_to="gdrive_service_account_file",
        verbose_name="Service Account File",
        blank=True,
        null=True,
        help_text="Required only for Service Account method. Google Service Account JSON file for Google Workspace accounts.",
    )
    
    # OAuth fields (for personal and business accounts)
    oauth_client_id = models.CharField(
        max_length=500,
        blank=True,
        null=True,
        verbose_name="OAuth Client ID",
        help_text="Required for OAuth method. Get this from Google Cloud Console > APIs & Services > Credentials."
    )
    oauth_client_secret = models.CharField(
        max_length=500,
        blank=True,
        null=True,
        verbose_name="OAuth Client Secret",
        help_text="Required for OAuth method. Get this from Google Cloud Console > APIs & Services > Credentials."
    )
    oauth_refresh_token = models.TextField(
        blank=True,
        null=True,
        verbose_name="OAuth Refresh Token",
        help_text="Auto-generated during OAuth authentication process. Do not edit manually."
    )
    
    gdrive_folder_id = models.CharField(
        max_length=255,
        verbose_name="Google Drive Folder ID",
        help_text="The ID of the Google Drive folder where backups will be stored. "
                 "You can get this from the folder URL in Google Drive."
    )
    backup_media = models.BooleanField(blank=True, null=True)
    backup_db = models.BooleanField(blank=True, null=True)
    interval = models.BooleanField(blank=True, null=True)
    fixed = models.BooleanField(blank=True, null=True)
    seconds = models.IntegerField(blank=True, null=True)
    hour = models.IntegerField(blank=True, null=True)
    minute = models.IntegerField(blank=True, null=True)
    active = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        # Check if there's an existing instance
        if self.interval == False:
            self.seconds = None
        if self.fixed == False:
            self.hour = None
            self.minute = None
        if GoogleDriveBackup.objects.exists():
            # Get the existing instance
            existing_instance = GoogleDriveBackup.objects.first()
            # Update the fields of the existing instance with the new data
            for field in self._meta.fields:
                if field.name != "id":  # Avoid changing the primary key
                    setattr(existing_instance, field.name, getattr(self, field.name))
            # Save the updated instance
            super(GoogleDriveBackup, existing_instance).save(*args, **kwargs)
            return existing_instance
        else:
            # If no existing instance, proceed with regular save
            super(GoogleDriveBackup, self).save(*args, **kwargs)
            return self
