"""Facebook platform for notify component."""
import json
import logging

from aiohttp.hdrs import CONTENT_TYPE
import requests
import voluptuous as vol

from homeassistant.components.notify import (
    ATTR_DATA,
    ATTR_TARGET,
    PLATFORM_SCHEMA,
    BaseNotificationService,
)
from homeassistant.const import CONTENT_TYPE_JSON
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

CONF_PAGE_ACCESS_TOKEN = "page_access_token"
BASE_URL = "https://graph.facebook.com/v2.6/me/messages"
CREATE_BROADCAST_URL = "https://graph.facebook.com/v2.11/me/message_creatives"
SEND_BROADCAST_URL = "https://graph.facebook.com/v2.11/me/broadcast_messages"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {vol.Required(CONF_PAGE_ACCESS_TOKEN): cv.string}
)


def get_service(hass, config, discovery_info=None):
    """Get the Facebook notification service."""
    return FacebookNotificationService(config[CONF_PAGE_ACCESS_TOKEN])


class FacebookNotificationService(BaseNotificationService):
    """Implementation of a notification service for the Facebook service."""

    def __init__(self, access_token):
        """Initialize the service."""
        self.page_access_token = access_token

    def send_message(self, message="", **kwargs):
        """Send some message."""
        payload = {"access_token": self.page_access_token}
        targets = kwargs.get(ATTR_TARGET)
        data = kwargs.get(ATTR_DATA)

        body_message = {"text": message}

        if data is not None:
            body_message.update(data)
            # Only one of text or attachment can be specified
            if "attachment" in body_message:
                body_message.pop("text")

        if not targets:
            _LOGGER.error("At least 1 target is required")
            return

        # broadcast message
        if targets[0].lower() == "broadcast":
            broadcast_create_body = {"messages": [body_message]}
            _LOGGER.debug("Broadcast body %s : ", broadcast_create_body)

            resp = requests.post(
                CREATE_BROADCAST_URL,
                data=json.dumps(broadcast_create_body),
                params=payload,
                headers={CONTENT_TYPE: CONTENT_TYPE_JSON},
                timeout=10,
            )
            _LOGGER.debug("FB Messager broadcast id %s : ", resp.json())

            # at this point we get broadcast id
            broadcast_body = {
                "message_creative_id": resp.json().get("message_creative_id"),
                "notification_type": "REGULAR",
            }

            resp = requests.post(
                SEND_BROADCAST_URL,
                data=json.dumps(broadcast_body),
                params=payload,
                headers={CONTENT_TYPE: CONTENT_TYPE_JSON},
                timeout=10,
            )
            if resp.status_code != 200:
                log_error(resp)

        # non-broadcast message
        else:
            for target in targets:
                # If the target starts with a "+", it's a phone number,
                # otherwise it's a user id.
                if target.startswith("+"):
                    recipient = {"phone_number": target}
                else:
                    recipient = {"id": target}

                body = {
                    "recipient": recipient,
                    "message": body_message,
                    "messaging_type": "MESSAGE_TAG",
                    "tag": "ACCOUNT_UPDATE",
                }
                resp = requests.post(
                    BASE_URL,
                    data=json.dumps(body),
                    params=payload,
                    headers={CONTENT_TYPE: CONTENT_TYPE_JSON},
                    timeout=10,
                )
                if resp.status_code != 200:
                    log_error(resp)


def log_error(response):
    """Log error message."""
    obj = response.json()
    error_message = obj["error"]["message"]
    error_code = obj["error"]["code"]

    _LOGGER.error(
        "Error %s : %s (Code %s)", response.status_code, error_message, error_code
    )

@@ -525,165 +525,8 @@
 ges%22
-%0ACREATE_BROADCAST_URL = %22https://graph.facebook.com/v2.11/me/message_creatives%22%0ASEND_BROADCAST_URL = %22https://graph.facebook.com/v2.11/me/broadcast_messages%22
 %0A%0APL
@@ -1653,46 +1653,29 @@
     
-# broadcast message%0A        if
+for target in
  targets
 %5B0%5D.
@@ -1674,421 +1674,292 @@
 gets
-%5B0%5D.lower() == %22broadcast%22:%0A            broadcast_create_body = %7B%22messages%22: %5Bbody_message%5D%7D%0A            _LOGGER.debug(%22Broadcast body %25s : %22, broadcast_create_body)%0A%0A            resp = requests.post(%0A                CREATE_BROADCAST_URL,%0A                data=json.dumps(broadcast_create_body),%0A                params=payload,%0A                headers=%7BCONTENT_TYPE: CONTENT_TYPE_JSON%7D,%0A                timeout=10,
+:%0A            # If the target starts with a %22+%22, it's a phone number,%0A            # otherwise it's a user id.%0A            if target.startswith(%22+%22):%0A                recipient = %7B%22phone_number%22: target%7D%0A            else:%0A                recipient = %7B%22id%22: target%7D%0A%0A            body = %7B
 %0A   
@@ -1971,287 +1971,164 @@
     
-)%0A
     
-        _LOGGER.debug(%22FB Messager broadcast id %25s : %22, resp.json())%0A%0A            # at this point we get broadcast id%0A            broadcast_body = %7B%0A                %22message_creative_id%22: resp.json().get(%22message_creative_id%22),%0A                %22notification_type%22: %22REGULAR
+%22recipient%22: recipient,%0A                %22message%22: body_message,%0A                %22messaging_type%22: %22MESSAGE_TAG%22,%0A                %22tag%22: %22ACCOUNT_UPDATE
 %22,%0A 
@@ -2140,17 +2140,16 @@
       %7D%0A
-%0A
         
@@ -2194,22 +2194,12 @@
     
-SEND_BROADCAST
+BASE
 _URL
@@ -2236,18 +2236,8 @@
 mps(
-broadcast_
 body
@@ -2449,946 +2449,8 @@
 p)%0A%0A
-        # non-broadcast message%0A        else:%0A            for target in targets:%0A                # If the target starts with a %22+%22, it's a phone number,%0A                # otherwise it's a user id.%0A                if target.startswith(%22+%22):%0A                    recipient = %7B%22phone_number%22: target%7D%0A                else:%0A                    recipient = %7B%22id%22: target%7D%0A%0A                body = %7B%0A                    %22recipient%22: recipient,%0A                    %22message%22: body_message,%0A                    %22messaging_type%22: %22MESSAGE_TAG%22,%0A                    %22tag%22: %22ACCOUNT_UPDATE%22,%0A                %7D%0A                resp = requests.post(%0A                    BASE_URL,%0A                    data=json.dumps(body),%0A                    params=payload,%0A                    headers=%7BCONTENT_TYPE: CONTENT_TYPE_JSON%7D,%0A                    timeout=10,%0A                )%0A                if resp.status_code != 200:%0A                    log_error(resp)%0A%0A
 %0Adef

Remove facebook broadcast api (#32517)