# -*- coding: UTF-8 -*-
import os
import sys
import subprocess
from re import compile
import unicodedata
from .rpc import server_version
from app import __version__

_slugify_strip_re = compile(r'[^\w\s-]')
_slugify_hyphenate_re = compile(r'[-\s]+')


def test_server_version(host, port):
    version = server_version(host, port)
    if not version:
        return False
    return version.split('.')[:2] == __version__.split('.')[:2]


def slugify(value):
    if not isinstance(value, str):
        value = value.decode('utf-8')
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = value.decode('utf-8')
    value = _slugify_strip_re.sub('', value).strip().lower()
    return _slugify_hyphenate_re.sub('-', value)


def file_open(filename, type, direct_print=False):
    def save():
        pass

    name = filename.split('.')

    if 'odt' in name:
        direct_print = False

    if os.name == 'nt':
        operation = 'open'
        if direct_print:
            operation = 'print'
        try:
            os.startfile(os.path.normpath(filename), operation)
        except WindowsError:
            save()
    elif sys.platform == 'darwin':
        try:
            subprocess.Popen(['/usr/bin/open', filename])
        except OSError:
            save()
    else:
        if direct_print:
            try:
                subprocess.Popen(['lp', filename])
            except:
                direct_print = False

        if not direct_print:
            try:
                subprocess.Popen(['xdg-open', filename])
            except OSError:
                pass
