import sys
import subprocess
import os
from ps_socket import socket
import time


class WindowCls:

    def get_slected_text(self) -> str:
        result = socket.post_and_recv_result("get-selected-text", {})
        return result

    def append_msg(self, message: str, type='info'):
        if not isinstance(message, str):
            message = repr(message)
        socket.post("append-msg", {"message": message, "type": type})

    def show_operation(self, text: str):
        socket.post("show-operation", {"text": text})

    def screenshot(self, name):
        socket.post("screenshot", {"name": name})

    def confirm(self, message: str) -> bool:
        return socket.post_and_recv_result("confirm", {"message": message})

    def maximize(self):
        socket.post("maximize", {})

    def open_file_with_system(self, file_path, wait: bool):
        process_fn = subprocess.run if wait else subprocess.Popen
        if sys.platform.startswith('linux'):
            process_fn(['xdg-open', file_path])
        elif sys.platform.startswith('darwin'):
            process_fn(['open', file_path])
        elif sys.platform.startswith('win32') or sys.platform.startswith('cygwin'):
            os.startfile(file_path)
        else:
            raise OSError('Unsupported operating system')

    def open_program(self, file_path, wait: bool):
        process_fn = subprocess.run if wait else subprocess.Popen
        process_fn([file_path])

    def execute_javaScript(self, js_code: str):
        result = socket.post_and_recv_result("executeJavaScript", {"code": js_code})
        if not result["ok"]:
            raise Exception(result["value"])
        return result["value"] if "value" in result else None