import requests

LINE_URL = "https://api.line.me/v2/bot"
class CraftMessage:
    def message_push(to, messageObject):
        json = {
            "to": to,
            "messages":messageObject
            }
        return json
    
    def message_narrow(audienceGroupId, messageObject):
        json = {
            "messages":messageObject,
            "recipient": {
                "type": "operator",
                "and": [
                    {
                        "type": "audience",
                        "audienceGroupId": int(audienceGroupId)
                    }
                ]
                }
            }
        return json
    def image_map_single(altText, imageLink, ladingpage, width, height):
        data =  {
            "type": "imagemap",
            "baseUrl": imageLink,
            "altText": altText,
            "baseSize": {
                "width": int(width),
                "height": int(height)
            },  "actions": [
                {
                "type": "uri",
                "linkUri": ladingpage,
                "area": {
                    "x": 0,
                    "y": 0,
                    "width": int(width),
                    "height": int(height)
                }
                }]
            }
        return data

    def message_single(text):
        data = {
            "type": "text",
            "text": text
        }
        return data

    def quick_reply(text, bubble1, bubble2):
        data = {
            "type": "text",
            "text": text,
            "quickReply": { 
            "items": [
                {
                    "type": "action",
                    "action": {
                    "type": "message",
                    "label": bubble1,
                    "text": bubble1
                    }
                },
                {
                    "type": "action",
                    "action": {
                    "type": "message",
                    "label": bubble2,
                    "text": bubble2
                    }
                }]
            }
        }
        return data

    def message_push_multiple(to, messageObject):
        data = {
            "to": to,
            "messages":messageObject
            
        }

        return data


    def message_push(to, messageObject):
        data = {
            "to": to,
            "messages":[
                messageObject
            ]
        }

        return data


    def audience_narrow_exclude(messages, audience_id, audience_id_exclude):
        # Define the payload as a Python dictionary
        payload = {
            "messages": messages,
            "recipient": {
                "type": "operator",
                "and": [
                    {
                        "type": "audience",
                        "audienceGroupId": audience_id
                    },
                    {
                        "type": "operator",
                        "not": {
                            "type": "audience",
                            "audienceGroupId": audience_id_exclude
                        }
                    }
                ]
            }
        }

        return payload


    def audience_narrow(messages, audience_id):
        # Define the payload as a Python dictionary
        payload = {
            "messages": messages,
            "recipient": {
                "type": "operator",
                "and": [
                    {
                        "type": "audience",
                        "audienceGroupId": audience_id
                    }
                ]
            }
        }

        return payload
    
    def recipient_main(operator=None, audience=[]):
        for a in audience:
            if a['type'] == 'major':
                mainAudienceID = a['id']
                break
        
        recipient = {
                "type": "operator",
                f"{operator}": [
                    {
                        "type": "audience",
                        "audienceGroupId": int(mainAudienceID)
                    }
                ]
            }
        
        if operator == 'and':
            audienceList = []
            for a in audience:
                if a['type'] == 'minor':
                    if a['operator'] == 'and':
                        minorObject =  {
                                "type": "audience",
                                "audienceGroupId": int(a['id'])
                            }
                    else:
                        minorObject = {
                            "type": "operator",
                            f"{a['operator']}": {
                                "type": "audience",
                                "audienceGroupId": int(a['id'])
                            }
                        }
                    audienceList.append(minorObject)
            
            recipient[f"{operator}"].extend(audienceList)
        elif operator == 'or':
            audienceList = []
            for a in audience:
                if a['type'] == 'minor':
                    minorObject = {
                            "type": "audience",
                            "audienceGroupId": int(a['id'])
                        }
                    audienceList.append(minorObject)
            
            recipient[f"{operator}"].extend(audienceList)
            
        return recipient
    
    def craft_narrow_message(messageObject=[], recipient=None):
        
        payload = {
            "messages": messageObject,
            "recipient": recipient
        }
        
        return payload

class Message:
    def __init__(self, access_token=None):
        self.access_token = access_token
        self.headers = {"Content-Type": "application/json", "Authorization": f"Bearer {self.access_token}"}
        
    def send_broad_message(self, payload=None):
        respone = requests.post(f'{LINE_URL}/message/broadcast', headers=self.headers, json=payload)
        return respone
    
    def send_narrow_message(self, payload=None):
        respone = requests.post(f'{LINE_URL}/message/narrowcast', headers=self.headers, json=payload)
        return respone
    
    def validate_narrowcast(self, payload=None):
        respone = requests.post(f'{LINE_URL}/message/validate/narrowcast', headers=self.headers, json=payload)
        return respone
    
class Audience:
    def __init__(self, access_token=None):
        self.access_token = access_token
        self.headers = {"Content-Type": "application/json", "Authorization": f"Bearer {self.access_token}"}

    
    def create_audience(self, name=None, audiences=[]):

        if len(audiences) > 0:
            audiences_list = []
            for au in audiences:
                audiences_list.append({"id": au})
        else:
            audiences_list = []
            
        body = {
            "description": name,
            "audiences": audiences_list
        }
        respone = requests.post(f'{LINE_URL}/audienceGroup/upload', headers=self.headers, json=body)
        return respone

    def delete_audience(self, audience_id=None):
        respone = requests.delete(f'{LINE_URL}/audienceGroup/{audience_id}', headers=self.headers)
        return respone
    
    def append_audience(self, audience_id=None, list_line_uid=[]):
        #Clean process
        cleandList = []
        for uid in list_line_uid:
            if uid != None and uid != '':
                cleandList.append(
                    {
                        'id': uid
                    }
                )
        
        #####
        body = {
            "audienceGroupId": int(audience_id),
            "audiences": cleandList
        }

        respone = requests.put(f'{LINE_URL}/audienceGroup/upload', headers=self.headers, json=body)
        return respone
    
    def get_audience_stat(self, audience_id=None):
        respone = requests.get(f'{LINE_URL}/audienceGroup/{audience_id}', headers=self.headers)
        return respone

    
    def get_list_audience_data(self):
        hasNextPage = True
        pack = []
        page = 1
        while hasNextPage:
            respone = requests.get(f'{LINE_URL}/audienceGroup/list?size=40&page={page}', headers=self.headers)
            data = respone.json()
            audienceGroups = data.get('audienceGroups')
            if len(audienceGroups) > 0:
                pack.extend(audienceGroups)

            page += 1
            hasNextPage = data.get('hasNextPage')

        return pack
    
class OA:
    def __init__(self, access_token=None):
        self.access_token = access_token
        self.headers = {"Content-Type": "application/json", "Authorization": f"Bearer {self.access_token}"}

    def getOAProfile(self):
        respone = requests.get(f"{LINE_URL}/info", headers=self.headers)
        return respone

    def getQuota(self):
        respone_quota = requests.get(f"{LINE_URL}/message/quota", headers=self.headers)
        quota_respone = respone_quota.json()
        quota = quota_respone.get('value')

        respone_quota_con = requests.get(f"{LINE_URL}/message/quota/consumption", headers=self.headers)
        quota_con_respone = respone_quota_con.json()
        quota_con = quota_con_respone.get('totalUsage')

        return {
            'quota': quota,
            'consumption': quota_con,
            'remaining': quota - quota_con
        }, 200
    
    def getHookEndpoint(self):
        respone = requests.get(f"{LINE_URL}/channel/webhook/endpoint", headers=self.headers)
        return respone.status_code, respone.content
    
    def putHookEndpoint(self, endpoint):
        data = {
            "endpoint": endpoint
        }
        respone = requests.put(f"{LINE_URL}/channel/webhook/endpoint", headers=self.headers, json=data)
        return respone.status_code, respone.content
    
    def getUserProfile(self, user_id):
        import requests
        url = f"https://api.line.me/v2/bot/profile/{user_id}"
        headers = {
            "Authorization": f"Bearer {self.access_token}",
            "Content-Type": "application/json"
        }
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Failed to get profile: {response.status_code} {response.text}")
