# coding=utf-8

from pathlib import Path

import elib
import pytest
from mockito import contains, patch, verify, when

from edlm.external_tools import MikTex, base


@pytest.fixture(name='mpm_file')
def _mpm_file():
    mpm_file = Path('./texmfs/config/miktex/config/miktex.ini')
    mpm_file.parent.mkdir(parents=True)
    yield mpm_file


@pytest.fixture(name='miktex')
def _miktex():
    when(base.BaseExternalTool)._is_installed().thenReturn(True)
    when(elib).run(contains('--version'), mute=True).thenReturn(('miktex version\ntext', 0))
    miktex = MikTex()
    miktex.install_dir = '.'
    yield miktex
    verify(base.BaseExternalTool)._is_installed()


def test_miktex_setup_create_new_mpm(miktex: MikTex):
    patch(MikTex, 'version', 'test')
    mpm_file = Path('./texmfs/config/miktex/config/miktex.ini')
    miktex.setup()
    assert mpm_file.exists()
    assert mpm_file.read_text(encoding='utf8') == """;;; DO NOT EDIT THIS FILE!


[MPM]
AutoInstall=1

"""


def test_miktex_setup_edit_mpm_add_section(mpm_file: Path, miktex: MikTex):
    mpm_file.write_text('some pre-existing content', encoding='utf8')
    patch(MikTex, 'version', 'test')
    miktex.setup()
    assert mpm_file.read_text(encoding='utf8') == """some pre-existing content
[MPM]
AutoInstall=1
"""


def test_miktex_setup_edit_mpm_add_line(mpm_file: Path, miktex: MikTex):
    mpm_file.write_text("""some pre-existing content
[MPM]
""", encoding='utf8')
    patch(MikTex, 'version', 'test')
    miktex.setup()
    assert mpm_file.read_text(encoding='utf8') == """some pre-existing content
[MPM]
AutoInstall=1
"""


def test_miktex_setup_edit_mpm_line(mpm_file: Path, miktex: MikTex):
    mpm_file.write_text(""";;; DO NOT EDIT THIS FILE!


[MPM]
AutoInstall=0

""", encoding='utf8')
    patch(MikTex, 'version', 'test')
    miktex.setup()
    assert mpm_file.read_text(encoding='utf8') == """;;; DO NOT EDIT THIS FILE!


[MPM]
AutoInstall=1

"""


def test_version(miktex: MikTex):
    when(base.BaseExternalTool).__call__('--version').thenReturn('miktex version\nnoise')
    miktex.setup()
    assert miktex.get_version() == 'version'
