import os
import socket
import logging

from django.views import View
from django.conf import settings
from django.shortcuts import render, redirect, HttpResponseRedirect

import google_auth_oauthlib
import google.oauth2.credentials
import googleapiclient.discovery
from google.oauth2 import credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import logging
from apps.process.models import ProcessedMedia
import requests
from django.conf import settings
from django.contrib import messages


# Create a logger for this file
logger = logging.getLogger(__file__)

# Create your views here.
class YoutubeAuthorize(View):
    def get(self,request,media_id,*args,**kwargs):
        if not request.user.is_authenticated:
            return redirect('accounts:signin')

        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(settings.JSON_PATH, scopes=settings.SCOPES)
        flow.redirect_uri= settings.REDIRECT_URI
        authorization_url, state = flow.authorization_url(
            # Enable offline access so that you can refresh an access token without
            # re-prompting the user for permission. Recommended for web server apps.
            access_type='offline',
            # Enable incremental authorization. Recommended as a best practice.
            include_granted_scopes='true'
        )

        # Store the state so the callback can verify the auth server response.
        request.session['media_id'] = media_id
        request.session['state'] = state

        return HttpResponseRedirect(authorization_url)


class YoutubeCallBack(View):
    def get(self,request,*args,**kwargs):
        if not request.user.is_authenticated:
            return redirect('accounts:signin')

        RETRIABLE_STATUS_CODES = [500, 502, 503, 504]

        state = request.session['state']
        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(settings.JSON_PATH, scopes=None, state=state)
        flow.redirect_uri = settings.REDIRECT_URI
        authorization_response = request.get_full_path()
        # print(colored(request.get_full_path(),"red"))
        flow.fetch_token(authorization_response=authorization_response)
        print(authorization_response)

        credentials = flow.credentials

        # request.session['video_id'] =
        final_video = None
        try:
            final_video = ProcessedMedia.objects.get(id=request.session['media_id'])
            print(final_video.video_path)
            logging.info(f'Video will be uploaded: {final_video.video_path}')
        except KeyError:
            final_video = None
        data = {}
        data['snippet']={}
        data['snippet']['title']= f'{final_video.media.title}'
        data['status']={}
        data['status']['privacyStatus']='private'

        response_upload=build("youtube",'v3',credentials=credentials)
        
        media = requests.get(final_video.url_video())
        with open("media/"+final_video.video_path,'wb') as f:
            f.write(media.content)
 
        request_upload = response_upload.videos().insert(
            part="snippet,status",
            body=data,
            media_body=MediaFileUpload("media/" + final_video.video_path)
        ).execute()
        # add thumbnail 
        # response_upload.thumbnails().set(
        #    videoId=request_upload.get("id"),
        #    media_body=MediaFileUpload(final_video.media.thumbnail)
        # ).execute()

        socket.setdefaulttimeout(60000)
        logging.info(f'Youtube Upload Response: {request_upload}')
        os.remove("media/" + final_video.video_path)     
        
        # if request_upload.status in RETRIABLE_STATUS_CODES:
        if request_upload['status'] in RETRIABLE_STATUS_CODES:
            messages.error(request, f"A retriable HTTP error { request_upload['status'] } occurred: { request_upload['content'] }")
        else: 
            video_url = f"https://www.youtube.com/watch?v={request_upload['id']}" 
            messages.success(
                request, 
                f"Your video (ID: { request_upload['id'] }) has been uploaded successfully. You can view it at: <a href='{ video_url }'  target='_blank'>{ video_url }</a>"
            )

        return redirect('landing:dashboard')
     