import telepot
import re
import locale

from who2pay import TOKEN
from who2pay.models import User, Bill, BillItem, BillItemUser
from who2pay.database import db_session, SUPER_ACCOUNT_ID

from sqlalchemy import or_, and_

from Queue import Queue
from telepot.delegate import pave_event_space, per_chat_id, create_open

MSG_BILL_CREATE_TEMPLATE = 'Simply type /create description to create new bill'
MSG_BILL_CREATE_TITLE_TEMPLATE = 'Please provide a title for the new bill'
MSG_BILL_ITEM_EDIT_TEMPLATE = 'To add a bill item, simply type ' + '_item description_*@*_2.5_'
MSG_BILL_FINISH_TEMPLATE = '/finish to complete the bill'
MSG_BILL_SEARCH_TEMPLATE = 'Enter text to search for your bills'
MSG_BILL_LIST_TEMPLATE = '*These are your bills{0}:*'
MSG_BILL_LIST_EMPTY_TEMPLATE = 'No bills created. Would you like to /create a bill'

MSG_WELCOME_TEMPLATE = 'Welcome to who2pay bot.\n' + MSG_BILL_CREATE_TEMPLATE

locale.setlocale(locale.LC_ALL, '')


class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)
        self._count = 0

    # TODO edit message for bill_title, item
    def on_chat_message(self, msg):
        print ('received', msg)

        msg_text = msg.get('text')
        # unique in this chat
        msg_id = msg.get('message_id')
        msg_sender = msg.get('from')
        msg_sender_id = msg_sender.get('id')

        self._count += 1
        user = db_session.query(User).filter(User.user_id == msg_sender_id).first()

        if user is None:
            new_user = User(msg_sender_id, msg_sender.get('username'),
                            msg_sender.get('first_name'), msg_sender.get('last_name'), None, SUPER_ACCOUNT_ID)
            db_session.add(new_user)
            db_session.commit()

            print ('new user:', user.username)
            self.sender.sendMessage(MSG_WELCOME_TEMPLATE, parse_mode='markdown')
            return

        else:
            print ('existing user:', user.username)

        bill_to_edit = db_session \
            .query(Bill) \
            .filter(and_(Bill.created_by_id == msg_sender_id, Bill.is_editing.is_(True))) \
            .first()
        has_pending_bill_to_edit = bill_to_edit is not None

        if has_pending_bill_to_edit:

            print ('pending bill to edit', bill_to_edit.title, bill_to_edit.description)
            match_finish = re.match('(/finish)(.*)', msg_text)
            match_item = re.match('(.*)@(\s*\d+?)((\d{1,16})(\.(\d{1,2})(\d*))?)$', msg_text)

            if match_finish:
                print ('mark bill as finished')
                bill_to_edit.is_editing = False
                bill_to_edit.update(msg_sender_id)
                db_session.commit()

                # TODO display bill summary
                self.sender.sendMessage('\'{0}\' completed'.format(bill_to_edit.title), parse_mode='markdown')

            elif match_item:
                print ('add bill item')
                item_title = match_item.group(1)
                item_price = match_item.group(3)

                bill_item = BillItem(bid=bill_to_edit.id, title=item_title, price=item_price, message_id=msg_id,
                                     created_by_id=msg_sender_id)
                print ('item:', item_title, 'price:', item_price)

                db_session.add(bill_item)
                db_session.commit()

                self.sender.sendMessage(
                    '\'{0}\' at {1} added'.format(bill_item.title, locale.currency(bill_item.price), '$') +
                    '\n' + MSG_BILL_FINISH_TEMPLATE, parse_mode='markdown')

            else:
                print ('neither /finish nor item editing')

                item_count = db_session \
                    .query(BillItem) \
                    .filter(BillItem.bill_id == bill_to_edit.id) \
                    .count()
                return_message = '\'{}\' still in editing mode.'.format(bill_to_edit.title)

                if item_count > 0:
                    return_message = return_message + '\n' + MSG_BILL_FINISH_TEMPLATE
                else:
                    return_message = return_message + '\n' + MSG_BILL_ITEM_EDIT_TEMPLATE

                self.sender.sendMessage(return_message, parse_mode='markdown')

        else:
            print ('no pending bills to edit')
            match_create = re.match('(/create)(.*)', msg_text)
            match_search = re.match('(/search)(.*)', msg_text)

            if match_create:
                bill_title = match_create.group(2).strip()
                print ('create bill title: ', bill_title)