# -*- coding: utf-8 -*-

# Copyright (C) 2008-2014 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

import logging
import datetime

import firebase_admin
from firebase_admin import messaging, credentials
from firebase_admin.exceptions import FirebaseError

from os import path

from xivo_agid import agid
from xivo_agid import dialplan_variables
from xivo_agid.handlers.userfeatures import UserFeatures



logger = logging.getLogger(__name__)

INIT_FB = False

try:    
    if(path.exists("/etc/xivo/xivo-mobile-firebase-adminsdk.json")):
        cred = credentials.Certificate("/etc/xivo/xivo-mobile-firebase-adminsdk.json")
        firebase_admin.initialize_app(cred)
        INIT_FB = True
    else:
        INIT_FB = False
        logger.warn('Firebase credentials file not found in /etc/xivo/xivo-mobile-firebase-adminsdk.json')
        logger.warn('Mobile App will not work on this XiVO server')
except FirebaseError as e:
        logger.error('Error during mobile_push_notification Firebase initialization: %s', e)
except Exception as e:
        logger.error('Error during mobile_push_notification initialization: %s', e)

def mobile_push_notification(agi, cursor, args, dry_run=False):
    if INIT_FB == False:
        agi.verbose("Firebase credentials not available. Will not be able to send push notification")
        agi.verbose("Exiting")
        return

    token = agi.get_variable(dialplan_variables.MOBILE_PUSH_TOKEN)
    caller = agi.get_variable(dialplan_variables.SRCNUM)

    android_config=messaging.AndroidConfig(
        ttl=datetime.timedelta(seconds=20),
        priority='high'
    )

    webpush_config=messaging.WebpushConfig(
        headers = {'Urgency': 'high'}
    )

    now = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")

    if token != UserFeatures.NOT_REGISTERED:
        agi.verbose('Token: %s' % token)
        message = messaging.Message(data={'title':'Incoming call', 'time': now, 'caller': caller},token=token, android=android_config, webpush=webpush_config)
        agi.verbose('Message: %s' % message)
        try:
            # TODO what about error during delivering?
            response = messaging.send(message, dry_run=dry_run)
            agi.verbose('Response: %s' % response)
        except ValueError as e:
            agi.verbose("Invalid input arguments: %s" % str(e))
            logger.error(f"Invalid input arguments: %s", e)
            raise
        except FirebaseError as e:
            agi.verbose("Error while sending message to FCM: %s" % str(e))
            logger.error(f"Error while sending message to FCM service: %s", e)
        else:
            agi.verbose('Response: %s', response)
            logger.debug("Response: %s", response)


agid.register(mobile_push_notification)
