from __future__ import unicode_literals

from ctypes import windll, byref, ArgumentError, c_char, c_long, c_ulong
from ctypes.wintypes import DWORD
from ..win32_types import CONSOLE_SCREEN_BUFFER_INFO, STD_OUTPUT_HANDLE, COORD, SMALL_RECT

import sys

__all__ = (
    'Win32Output',
)


def _coord_byval(coord):
    """
    Turns a COORD object into a c_long.
    This will cause it to be passed by value instead of by reference. (That is what I think at least.)

    When runing ``ptipython`` is run (only with IPython), we often got the following error::

         Error in 'SetConsoleCursorPosition'.
         ArgumentError("argument 2: <class 'TypeError'>: wrong type",)
     argument 2: <class 'TypeError'>: wrong type

    It was solved by turning ``COORD`` parameters into a ``c_long`` like this.

    More info: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx
    """
    return c_long(coord.Y * 0x10000 | coord.X & 0xFFFF)


#: If True: write the output of the renderer also to the following file. This
#: is very useful for debugging. (e.g.: to see that we don't write more bytes
#: than required.)
_DEBUG_RENDER_OUTPUT = False
_DEBUG_RENDER_OUTPUT_FILENAME = r'prompt-toolkit-windows-output.log'


class Win32Output(object):
    """
    """
    def __init__(self, stdout, use_complete_width=False):
        self.use_complete_width = use_complete_width

        self._buffer = []
        self.stdout = stdout
        self.hconsole = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

        self.color_lookup_table = ColorLookupTable()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG = open(_DEBUG_RENDER_OUTPUT_FILENAME, 'ab')

    def write(self, data):
        self._buffer.append(data)

    def get_size(self):
        from prompt_toolkit.layout.screen import Size
        info = self._screen_buffer_info()

        # We take the width of the *visible* region as the size. Not the width
        # of the complete screen buffer. (Unless use_complete_width has been
        # set.)
        if self.use_complete_width:
            width = info.dwSize.X
        else:
            width = info.srWindow.Right - info.srWindow.Left

        height = info.srWindow.Bottom - info.srWindow.Top

        # We avoid the right margin, windows will wrap otherwise.
        maxwidth = info.dwSize.X - 1
        width = min(maxwidth, width)

        # Create `Size` object.
        return Size(rows=height, columns=width)

    def _winapi(self, func, *a, **kw):
        """
        Flush and call win API function.
        """
        self.flush()

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
            self.LOG.write(b'     ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
            self.LOG.flush()

        try:
            return func(*a, **kw)
        except ArgumentError as e:
            if _DEBUG_RENDER_OUTPUT:
                self.LOG.write(('    Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8'))

    def _screen_buffer_info(self):
        """
        Return Screen buffer info.
        """
        sbinfo = CONSOLE_SCREEN_BUFFER_INFO()
        success = self._winapi(windll.kernel32.GetConsoleScreenBufferInfo,
                               self.hconsole, byref(sbinfo))
        if success:
            return sbinfo

    def erase_screen(self):
        start = COORD(0, 0)
        sbinfo = self._screen_buffer_info()
        length = sbinfo.dwSize.X * sbinfo.dwSize.Y

        self.cursor_goto(row=0, column=0)
        self._erase(start, length)

    def erase_down(self):
        sbinfo = self._screen_buffer_info()
        size = sbinfo.dwSize

        start = sbinfo.dwCursorPosition
        length = ((size.X - size.X) + size.X * (size.Y - sbinfo.dwCursorPosition.Y))

        self._erase(start, length)

    def erase_end_of_line(self):
        """
        """
        sbinfo = self._screen_buffer_info()
        start = sbinfo.dwCursorPosition
        length = sbinfo.dwSize.X - sbinfo.dwCursorPosition.X

        self._erase(start, length)

    def _erase(self, start, length):
        chars_written = c_ulong()

        self._winapi(windll.kernel32.FillConsoleOutputCharacterA,
                     self.hconsole, c_char(b' '), DWORD(length), _coord_byval(start),
                     byref(chars_written))

        # Reset attributes.
        sbinfo = self._screen_buffer_info()
        self._winapi(windll.kernel32.FillConsoleOutputAttribute,
                     self.hconsole, sbinfo.wAttributes, length, _coord_byval(start),
                     byref(chars_written))

    def reset_attributes(self):
        self._winapi(windll.kernel32.SetConsoleTextAttribute, self.hconsole, 15)  # White

    def set_attributes(self, fgcolor, bgcolor, bold=False, underline=False):
        i = self.color_lookup_table.lookup_color(fgcolor, bgcolor)
        self._winapi(windll.kernel32.SetConsoleTextAttribute, self.hconsole, i)

    def disable_autowrap(self):
        # Not supported by Windows.
        pass

    def enable_autowrap(self):
        # Not supported by Windows.
        pass

    def cursor_goto(self, row=0, column=0):
        pos = COORD(x=column, y=row)
        self._winapi(windll.kernel32.SetConsoleCursorPosition,
                     self.hconsole, _coord_byval(pos))

    def cursor_up(self, amount):
        sr = self._screen_buffer_info().dwCursorPosition
        pos = COORD(sr.X, sr.Y - amount)
        success = self._winapi(windll.kernel32.SetConsoleCursorPosition,
                               self.hconsole, _coord_byval(pos))

    def cursor_down(self, amount):
        self.cursor_up(-amount)

    def cursor_forward(self, amount):
        sr = self._screen_buffer_info().dwCursorPosition
        assert sr.X + amount >= 0, 'Negative cursor position: x=%r amount=%r' % (sr.X, amount)

        pos = COORD(max(0, sr.X + amount), sr.Y)
        success = self._winapi(windll.kernel32.SetConsoleCursorPosition,
                               self.hconsole, _coord_byval(pos))

    def cursor_backward(self, amount):
        self.cursor_forward(-amount)

    def flush(self):
        """
        Write to output stream and flush.
        """
        if not self._buffer:
            # Only flush stdout buffer. (It could be that Python still has
            # something in its buffer. -- We want to be sure to print that in
            # the correct color.)
            self.stdout.flush()
            return

        data = ''.join(self._buffer)

        if _DEBUG_RENDER_OUTPUT:
            self.LOG.write(('%r' % data).encode('utf-8') + b'\n')
            self.LOG.flush()

        # Write to output
        self.stdout.write(data)
        self.stdout.flush()

        self._buffer = []

    def get_rows_below_cursor_position(self):
        info = self._screen_buffer_info()
        return info.srWindow.Bottom - info.dwCursorPosition.Y  # - 1

    def scroll_buffer_to_prompt(self):
        """
        To be called before drawing the prompt. This should scroll the console
        to left, with the cursor at the bottom (if possible).
        """
        # Get current window size
        info = self._screen_buffer_info()
        sr = info.srWindow
        cursor_pos = info.dwCursorPosition

        result = SMALL_RECT()

        # Scroll to the left.
        result.Left = 0
        result.Right = sr.Right - sr.Left

        # Scroll vertical
        win_height = sr.Bottom - sr.Top
        result.Bottom = max(win_height, cursor_pos.Y)
        result.Top = result.Bottom - win_height

        # Scroll API
        success = self._winapi(windll.kernel32.SetConsoleWindowInfo,
                               self.hconsole, True, byref(result))


class FOREGROUND_COLOR:
    BLACK     = 0x0000
    BLUE      = 0x0001
    GREEN     = 0x0002
    CYAN      = 0x0003
    RED       = 0x0004
    MAGENTA   = 0x0005
    YELLOW    = 0x0006
    GREY      = 0x0007
    INTENSITY = 0x0008  # Foreground color is intensified.


class BACKROUND_COLOR:
    BLACK     = 0x0000
    BLUE      = 0x0010
    GREEN     = 0x0020
    CYAN      = 0x0030
    RED       = 0x0040
    MAGENTA   = 0x0050
    YELLOW    = 0x0060
    GREY      = 0x0070
    INTENSITY = 0x0080  # Background color is intensified.


class ColorLookupTable(object):
    """
    Inspired by pygments/formatters/terminal256.py
    """
    def __init__(self):
        self._win32_colors = self._build_color_table()
        self.best_match = {}  # Cache

    def _build_color_table(self):
        """
        Build an RGB-to-256 color conversion table
        """
        FG = FOREGROUND_COLOR
        BG = BACKROUND_COLOR

        return [
            (0x00, 0x00, 0x00, FG.BLACK, BG.BLACK),
            (0x00, 0x00, 0xaa, FG.BLUE, BG.BLUE),
            (0x00, 0xaa, 0x00, FG.GREEN, BG.GREEN),
            (0x00, 0xaa, 0xaa, FG.CYAN, BG.CYAN),
            (0xaa, 0x00, 0x00, FG.RED, BG.RED),
            (0xaa, 0x00, 0xaa, FG.MAGENTA, BG.MAGENTA),
            (0xaa, 0xaa, 0x00, FG.YELLOW, BG.YELLOW),
            (0x88, 0x88, 0x88, FG.GREY, BG.GREY),

            (0x44, 0x44, 0xff, FG.BLUE | FG.INTENSITY, BG.BLUE | BG.INTENSITY),
            (0x44, 0xff, 0x44, FG.GREEN | FG.INTENSITY, BG.GREEN | BG.INTENSITY),
            (0x44, 0xff, 0xff, FG.CYAN | FG.INTENSITY, BG.CYAN | BG.INTENSITY),
            (0xff, 0x44, 0x44, FG.RED | FG.INTENSITY, BG.RED | BG.INTENSITY),
            (0xff, 0x44, 0xff, FG.MAGENTA | FG.INTENSITY, BG.MAGENTA | BG.INTENSITY),
            (0xff, 0xff, 0x44, FG.YELLOW | FG.INTENSITY, BG.YELLOW | BG.INTENSITY),

            (0xff, 0xff, 0xff, FG.GREY | FG.INTENSITY, BG.GREY | BG.INTENSITY),
        ]

    def _closest_color(self, r, g, b):
        distance = 257 * 257 * 3  # "infinity" (>distance from #000000 to #ffffff)
        fg_match = 0
        bg_match = 0

        for r_, g_, b_, fg_, bg_ in self._win32_colors:
            rd = r - r_
            gd = g - g_
            bd = b - b_

            d = rd * rd + gd * gd + bd * bd

            if d < distance:
                fg_match = fg_
                bg_match = bg_
                distance = d
        return fg_match, bg_match

    def _color_indexes(self, color):
        indexes = self.best_match.get(color, None)
        if indexes is None:
            try:
                rgb = int(str(color), 16)
            except ValueError:
                rgb = 0

            r = (rgb >> 16) & 0xff
            g = (rgb >> 8) & 0xff
            b = rgb & 0xff
            indexes = self._closest_color(r, g, b)
            self.best_match[color] = indexes
        return indexes

    def lookup_color(self, fg_color, bg_color):
        fg_index = self._color_indexes(fg_color)[0]
        bg_index = self._color_indexes(bg_color)[1]

        if fg_index == 0:
            fg_index = FOREGROUND_COLOR.GREY

        return fg_index | bg_index
