from flask import Blueprint, request
import requests
import logging
from datetime import datetime, timedelta
from firebase.firebase import Firebase
import pytz 
import utility.function as func
import os
import time
logging.basicConfig(level=logging.INFO)

profile = Blueprint('profile', __name__, url_prefix='/profile')

fb = Firebase(host=os.environ.get("FIREBASE_HOST"))
timezone = pytz.timezone('Asia/Bangkok')

@profile.route('/',  methods=['POST'])
@profile.route('',  methods=['POST'])
def profile_view():
    
    # dateStr = datetime.now(timezone).date().strftime("%Y%m%d")
    # hourStr = (datetime.now(timezone) - timedelta(hours=1)).strftime("%H")
    account = fb.db.reference().child("account").get(shallow=True)
    for acc in account:
        # check acc process
        userInRange = []
        accActive = []

        # accountMapping = fb.db.reference().child("mapping/account").get(shallow=True)
        # status, accName = func.Function.checkAccountMapping(accountMapping=accountMapping, accountName=acc)

        # if status:
        #     accActive.append(accName)
        allProfile = fb.db.reference().child(f"account/{acc}/profile").get(shallow=True)
        # profileTemp = fb.db.reference().child(f"account/{acc}").get(shallow=True)
        # for page in profileTemp:
        #     pageProfile = fb.db.reference().child(f"account/{acc}/{page}/profile").get(shallow=True)
        for id in allProfile:
            proUpdate = fb.db.reference().child(f"account/{acc}/profile/{id}/updated_at").get()
            updated_at = datetime.fromisoformat(proUpdate)
            now = datetime.now(updated_at.tzinfo)
            if now.replace(minute=0, second=0, microsecond=0) - timedelta(hours=1) <= datetime.fromisoformat(proUpdate) <= now.replace(minute=0, second=0, microsecond=0):
                pro = fb.db.reference().child(f"account/{acc}/profile/{id}").get()
                userInRange.append(pro)

        if userInRange:
            from bigquery.bq import BigQuery
            bq = BigQuery()
            #Delete data from temp table
            bq.delete_data(project_name='customer-360-profile', dataset_name='client_' + acc, table_name='customer_profile_temp')
            
            loadData = []
            for user in userInRange:
                transformed_data = func.Function.transformProfiletoBQ(user)
                loadData.append(transformed_data)

            error = bq.load_data(target_table=f"client_{acc}.customer_profile_temp", data=loadData)
            if error:
                logging.error(f"Error loading data to BigQuery: {error}")
            else:
                logging.info(f"Data loaded to BigQuery for eventId")

            time.sleep(10)
            # Process update when match
            condition = "ON (ori.user_pseudo_id = temp.user_pseudo_id) "
            bq.delete_when_match(project_name='customer-360-profile', dataset_name_ori='client_' + acc, table_name_ori='customer_profile', dataset_name_temp='client_' + acc, table_name_temp='customer_profile_temp', condition=condition)
            bq.load_data(target_table=f"client_{acc}.customer_profile", data=loadData)
    return {'status': 'success', 'message': 'Profile data processed successfully'}, 200
            