import datetime
import json
import random
import string

from typing import Dict
from sms_counter import SMSCounter


class CreateMessageResponse: 
    def __init__(self, request):
        self.id = self.generate_id()
        self.owner = request['from']
        self.applicationId = request['applicationId']
        self.time = str(datetime.datetime.utcnow().isoformat())
        self.segmentCount = 1
        self.direction = 'out'

        if type(request['to']) is str:
            self.to = [request['to']]
        else:
            self.to = request['to']

        self.mfrom = request['from']
        if 'media' in request:
            self.media = request['media']
        if 'text' in request:
            self.text = request['text']
        if 'tag' in request:
            self.tag = request['tag']
        if 'priority' in request:
            self.priority = request['priority']
    

    def calculate_segments(self, message) -> int:
        count = SMSCounter.count(message)
        return count['messages']
    

    def generate_id(self) -> str:
        pre = random.randint(1400000000000,1799999999999)
        return str(pre) + ''.join(random.choice(string.ascii_lowercase) for x in range(16))
   

    def to_json(self) -> str:
        dict_response = {
            'id': self.id,
            'owner': self.owner,
            'applicationId': self.applicationId,
            'time': self.time,
            'direction': self.direction,
            'to': self.to,
            'from': self.mfrom
        }
        
        if hasattr(self, 'media'): dict_response['media'] = self.media
        if hasattr(self, 'text'): 
            dict_response['text'] = self.text
            dict_response['segmentCount'] = self.calculate_segments(self.text)
        if hasattr(self, 'tag'): dict_response['tag'] = self.tag
        if hasattr(self, 'priority'): dict_response['priority'] = self.priority
        return json.dumps(dict_response)

[((36, 16, 36, 41), 'sms_counter.SMSCounter.count', 'SMSCounter.count', ({(36, 33, 36, 40): 'message'}, {}), '(message)', False, 'from sms_counter import SMSCounter\n'), ((41, 14, 41, 57), 'random.randint', 'random.randint', ({(41, 29, 41, 42): '1400000000000', (41, 43, 41, 56): '1799999999999'}, {}), '(1400000000000, 1799999999999)', False, 'import random\n'), ((62, 15, 62, 40), 'json.dumps', 'json.dumps', ({(62, 26, 62, 39): 'dict_response'}, {}), '(dict_response)', False, 'import json\n'), ((15, 24, 15, 50), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ({}, {}), '()', False, 'import datetime\n'), ((42, 34, 42, 71), 'random.choice', 'random.choice', ({(42, 48, 42, 70): 'string.ascii_lowercase'}, {}), '(string.ascii_lowercase)', False, 'import random\n')]