# -*- coding: future_fstrings -*-
# Copyright 2018 Brandon Shelley. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Cursor controls for console output.

This module adds show and hide cursor controls for console output.

    cursor: the main class exported by this module.
"""

from __future__ import unicode_literals, print_function
from builtins import *

import sys
import os

import fylmlib.config as config

if os.name == 'nt':
    import ctypes

    class _CursorInfo(ctypes.Structure):
        _fields_ = [("size", ctypes.c_int),
                    ("visible", ctypes.c_byte)]

class cursor:
    """Main class for cursor controls.

    All methods are class methods, thus this class should never be instantiated.
    """

    @classmethod
    def hide(cls):
        """Hides the cursor in the console.
        """
        if not config.plaintext:
            try:
                if os.name == 'nt':
                    ci = _CursorInfo()
                    handle = ctypes.windll.kernel32.GetStdHandle(-11)
                    ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
                    ci.visible = False
                    ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
                elif os.name == 'posix':
                    sys.stdout.write("\033[?25l")
                    sys.stdout.flush()
            except Exception:
                pass

    @classmethod            
    def show(cls):
        """Shows the cursor in the console.
        """
        if not config.plaintext:
            try:
                if os.name == 'nt':
                    ci = _CursorInfo()
                    handle = ctypes.windll.kernel32.GetStdHandle(-11)
                    ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
                    ci.visible = True
                    ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
                elif os.name == 'posix':
                    sys.stdout.write("\033[?25h")
                    sys.stdout.flush()
            except Exception:
                pass