# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function

import re
from decimal import Decimal
import pytz
from ..handhistory import _Player, _SplittableHandHistory, _BaseFlop
from ..card import Card
from ..hand import Combo
from ..constants import Limit, Game, GameType, Currency, Action
from .._common import _make_int


__all__ = ['FullTiltPokerHandHistory']


class _Flop(_BaseFlop):
    def __init__(self, flop, initial_pot):
        self._initial_pot = self.pot = initial_pot
        self.actions = None
        self.cards = None
        self._parse_cards(flop[0])
        self._parse_actions(flop[1:])

    def _parse_cards(self, boardline):
        # print(boardline)
        self.cards = (Card(boardline[1:3]), Card(boardline[4:6]), Card(boardline[7:9]))

    def _parse_actions(self, actionlines):
        actions = []
        for line in actionlines:
            if line.startswith('Uncalled bet'):
                actions.append(self._parse_uncalled(line))
            elif 'raises to' in line:
                actions.append(self._parse_raise(line))
            elif 'wins the pot' in line:
                actions.append(self._parse_win(line))
            elif 'mucks' in line:
                actions.append(self._parse_muck(line))
            elif 'seconds left to act' in line:
                actions.append(self._parse_think(line))
            elif ' ' in line:
                actions.append(self._parse_player_action(line))
            else:
                raise
        self.actions = tuple(actions) if actions else None

    def _parse_uncalled(self, line):
        amount_start_index = 16
        space_after_amount_index = line.find(' ', amount_start_index)
        amount = line[amount_start_index:space_after_amount_index]
        name_start_index = line.find('to ') + 3
        name = line[name_start_index:]
        return name, Action.RETURN, Decimal(amount)

    def _parse_raise(self, line):
        first_space_index = line.find(' ')
        name = line[:first_space_index]
        amount_start_index = line.find('to ') + 3
        amount = line[amount_start_index:]
        return name, Action.RAISE, Decimal(amount)

    def _parse_win(self, line):
        first_space_index = line.find(' ')
        name = line[:first_space_index]
        first_paren_index = line.find('(')
        last_paren_index = -1
        amount = line[first_paren_index + 1:last_paren_index]
        self.pot = self._initial_pot + Decimal(amount)
        return name, Action.WIN, self.pot

    def _parse_muck(self, line):
        space_index = line.find(' ')
        name = line[:space_index]
        return name, Action.MUCK

    def _parse_think(self, line):
        space_index = line.find(' ')
        name = line[:space_index]
        return name, Action.THINK

    def _parse_player_action(self, line):
        space_index = line.find(' ')
        name = line[:space_index]
        end_action_index = line.find(' ', space_index + 1)
        # -1 means not found
        if end_action_index == -1:
            end_action_index = None  # until the end
        action = Action(line[space_index + 1:end_action_index])
        if end_action_index:
            amount = line[end_action_index + 1:]
            return name, action, Decimal(amount)
        else:
            return name, action


class FullTiltPokerHandHistory(_SplittableHandHistory):
    """Parses Full Tilt Poker hands the same way as PokerStarsHandHistory class."""

    date_format = '%H:%M:%S ET - %Y/%m/%d'
    tournament_level = None     # FTP hands doesn't contains tournament level information
    rake = None

    _TZ = pytz.timezone('US/Eastern')  # ET

    _split_re = re.compile(r" ?\*\*\* ?\n?|\n")
    # header patterns
    _header_re = re.compile(r"""
        ^Full[ ]Tilt[ ]Poker[ ]                                 # Poker Room
        Game[ ]\#(?P<ident>\d*):[ ]                             # Hand history id
        (?P<tournament_name>                                    # Tournament name
            \$?(?P<buyin>\d*)?                                  # buyin, not always there,
                                                                # part of tournament_name
        .*)[ ]                                                  # end of tournament_name
        \((?P<tournament_ident>\d*)\),[ ]                       # Tournament Number
        Table[ ](?P<table_name>\d*)[ ]-[ ]                      # Table name
        (?P<limit>NL|PL|FL|No Limit|Pot Limit|Fix Limit)[ ]     # limit
        (?P<game>.*?)[ ]-[ ]                                    # game
        (?P<sb>\d*)/(?P<bb>\d*)[ ]-[ ].*                        # blinds
        \[(?P<date>.*)\]$                                       # date in ET
        """, re.VERBOSE)
    _seat_re = re.compile(r"^Seat (\d): (.*) \(([\d,]*)\)$")