from django.contrib.auth import login

from BaseLib.BaseView import BaseView
from BaseLib.minio import minio_client


class ProfileView(BaseView):
    required_login = True
    endpoint = 'profile'
    view_file = 'profile.html'

    def get(self):
        self.context['err'] = 'err' in self.request.GET
        self.context['owner'] = not hasattr(self, 'customUser') or self.customUser == self.request.user
        self.context['account'] = getattr(self, 'customUser', None) or self.request.user

    def post_upload_photo(self):
        minio_client.put_object(self.request.FILES["file"].read(), f"profile_photos/{self.request.user.id}")
        return self

    def post_save_data(self):
        self.request.user.telegram_username = self.request.POST['telegram_username'] if self.request.POST['telegram_username'] else None
        self.request.user.telegram_id = int(self.request.POST['telegram_id']) if self.request.POST['telegram_id'] and str(self.request.POST['telegram_id']).isnumeric() else None
        self.request.user.email = self.request.POST['email'] if self.request.POST['email'] else None
        self.request.user.save()
        return '/profile'


    def post_change_password(self):
        if self.request.POST['password'] != self.request.POST['repeat']:
            return '/profile?err=true'
        self.request.user.set_password(self.request.POST['password'])
        self.request.user.save()
        login(self.request, self.request.user)
        return self
