# -*- coding: utf-8 -*-
"""Test walls."""

import flickrapi
import py
import pytest
import requests
import walls
try:
    # Python 3.x
    from configparser import ConfigParser
except ImportError:
    # Python 2.x
    from ConfigParser import SafeConfigParser as ConfigParser


@pytest.fixture
def config(tmpdir):
    f = tmpdir.join('config.ini')
    f.write('''
[walls]
api_key = myapikey
api_secret = myapisecret
tags = sanfrancisco
image_dir = {0}
width = 1920
height = 1080
    '''.format(tmpdir))
    return str(f)


@pytest.fixture
def config_obj(config):
    cfg = ConfigParser()
    cfg.read(config)
    return cfg


@pytest.fixture
def flickr():
    return flickrapi.FlickrAPI('myapikey', 'myapisecret')


class FakeResponse(requests.Response):

    """Used to emulate some requests behavior."""

    def __call__(self, *a, **kw):
        """Lets us use an instance to replace get()."""
        return self

    def iter_content(self, *a, **kw):
        for c in 'this is the data':
            yield c.encode()


class SystemExitContext(object):

    """Run pytest.raises, and check the error message."""

    def __init__(self, msg, capsys):
        self.raises = pytest.raises(SystemExit)
        self.capsys = capsys
        self.msg = msg

    def __enter__(self):
        return self.raises.__enter__()

    def __exit__(self, *args):
        assert self.capsys.readouterr()[1] == self.msg
        return self.raises.__exit__(*args)


@pytest.fixture
def errmsg(capsys):
    """Make sure we exit with the given error message."""
    def fixture(msg):
        return SystemExitContext(msg, capsys)
    return fixture


def test_stderr_and_exit(errmsg):
    """Make sure that stderr_and_exit (and therefore errmsg) works."""
    with errmsg('Some error message'):
        walls.stderr_and_exit('Some error message')


def test_usage(errmsg):
    """Make sure we print out the usage if the arguments are invalid."""
    with errmsg('Usage: walls [-c] [config_file]\n'):
        walls.main(['walls', 'config_file', 'blah'])


def test_default_config(config, monkeypatch):
    """Override expanduser to point to our temporary config file."""
    def my_expanduser(path):
        if path == '~/.wallsrc':
            return config
        return path
    monkeypatch.setattr('os.path.expanduser', my_expanduser)
    monkeypatch.setattr('walls.run', lambda *a: None)
    walls.main(['walls'])


def test_supplied_config(config):
    """Test a config file passed as a command line argument."""
    cfg = walls.load_config(config)
    assert cfg.get('walls', 'api_key') == 'myapikey'


def test_invalid_config(errmsg):
    """Make sure an error is raised if the config file can't be read."""
    with errmsg("Couldn't load config fake.ini\n"):
        walls.load_config('fake.ini')


def test_config_no_walls(tmpdir, errmsg):
    """Check for missing [walls] section."""
    f = tmpdir.join('config.ini')
    f.write('\n')
    with errmsg('Config missing [walls] section.\n'):
        walls.load_config(str(f))


def test_config_missing(tmpdir, errmsg):
    """Check behavior on missing config values."""
    f = tmpdir.join('config.ini')
    f.write('''