from flask import Flask, request, jsonify
from google.apps import meet_v2
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
import os.path

app = Flask(__name__)


# Define the required scopes for the Meet API
SCOPES = ['https://www.googleapis.com/auth/meetings.space.created']

class MeetingInfo:
    def __init__(self, id):
        self.name = id
        self.startTime = []
        self.endTime = []
        self.members = []

    def addParticipant(self, participant):
        self.members.append(participant)

def createToken():
    
    if os.path.exists('token.json'):
        #print("Jdu nacist token")
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    
    if creds and creds.expired and creds.refresh_token:
        #print("Jdu refreshnout token")
        creds.refresh(Request())
        
    return creds


def recordWithParticipants(recordName, i_client):
    request = meet_v2.ListParticipantsRequest(
        parent=recordName,
    )
    loc_result = i_client.list_participants(request=request)
    participants = list(loc_result.pages)
    if len(participants[0].participants) == 0:
        return False
    else:
        return True

def getSpaceInfo(spaceName, USER_CREDENTIALS):
    client = meet_v2.ConferenceRecordsServiceClient(credentials = USER_CREDENTIALS)
    request = meet_v2.ListConferenceRecordsRequest(filter='space.name = {}'.format(spaceName))
    page_result = client.list_conference_records(request=request)
    MeetingInfoList = []
    for conference_record in page_result:
        if recordWithParticipants(conference_record.name, client):
            loc_info = MeetingInfo(conference_record.name)
            request = meet_v2.ListParticipantsRequest(
            parent=conference_record.name,
        )
            loc_result = client.list_participants(request=request)
            for participant in loc_result:
                if participant:
                    partInfo = {
                                "signedin_user": {"user" : participant.signedin_user.user,
                                                  "display_name": participant.signedin_user.display_name},
                                "earliest_start_time": participant.earliest_start_time.ctime(),
                                "latest_end_time": participant.latest_end_time.ctime(),
                            }
                    loc_info.addParticipant(partInfo)
            
            loc_info.startTime = conference_record.start_time
            loc_info.endTime = conference_record.end_time
            MeetingInfoList.append(loc_info)
    return MeetingInfoList

def getInputData(request_data):
    if not request.json or 'space_name' not in request.json:
         return 'Error: No space_name provided', 400
    space_name = request_data.get('space_name')
    
    extracted_data = {
        'space_name': space_name
    }

    return extracted_data

@app.route('/space_info', methods=['POST'])
def space_info():
    request_data = request.json
    extracted_data = getInputData(request_data)
    spaceName = extracted_data["space_name"]
    #spaceName = "spaces/VVdybPv8GaQB"
    USER_CREDENTIALS = createToken()
    List = getSpaceInfo(spaceName, USER_CREDENTIALS)
    List2 = []
    for  i in range(len(List)):
        List2.append(List[i].__dict__)
    event = {
        "html": "<p>Info about meetings in given space.</p>",
        "List": List2,
        "SpaceName": spaceName
    }
    return jsonify({"Event": event})


if __name__ == '__main__':
    app.run(debug=True)
