# This file is part of AdMincer,
# Copyright (C) 2019 eyeo GmbH
#
# AdMincer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# AdMincer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AdMincer. If not, see <http://www.gnu.org/licenses/>.

"""Tests for image indexing."""

import pytest

import admincer.index as idx


@pytest.mark.parametrize('constructor', [idx.frag_index, idx.some_index])
def test_frag_index(fragdir, constructor):
    """Create an index of a directory with some fragments."""
    path = str(fragdir)
    fi = constructor(path)
    assert fi.root_path == path
    assert fi == {
        'red.gif': (10, 20),
        'green.png': (30, 40),
        'subdir/orange.jpg': (50, 60),
    }


def test_frag_add(fragdir):
    """Add image to fragment index."""
    fi = idx.frag_index(str(fragdir))
    fi.add_image('foo.png', fi.load_image('red.gif'))


@pytest.mark.parametrize('constructor', [idx.reg_index, idx.some_index])
def test_reg_index(regdir, constructor):
    """Create an index of a directory with images that have marked regions."""
    path = str(regdir)
    ri = constructor(path)
    assert ri.root_path == path
    assert ri == {
        'white2.png': [
            (10, 20, 20, 40, 'r1'),
            (50, 50, 80, 90, 'r2'),
        ],
        'blue3.png': [
            (10, 10, 20, 20, 'r1'),
            (40, 10, 50, 20, 'r1'),
            (10, 30, 60, 90, 'r3'),
        ],
        'black.gif': [],
    }


def test_reg_index_clipping(regdir_with_clipping):
    """Create an index of a directory with images that have marked regions."""
    path = str(regdir_with_clipping)
    ri = idx.reg_index(path)
    assert ri.root_path == path
    assert ri == {
        'red3.png': [
            (0, 80, 20, 90, 'r1'),
            (90, 0, 100, 20, 'r1'),
        ],

    }


def test_reg_index_yolo(regdir_var):
    """Region loading from YOLO-format files."""
    path = str(regdir_var)
    ri = idx.reg_index(path)
    assert ri.region_types == ['r1', 'r2', 'r3']
    assert ri == {
        'white2.png': [
            (0, 0, 15, 45, 'r1'),
            (65, 70, 100, 100, 'r2'),
        ],
        'blue3.png': [
            (10, 10, 20, 20, 'r1'),
            (40, 10, 50, 20, 'r2'),
            (10, 30, 60, 90, 'r3'),
        ],
        'black.gif': [
            (10, 10, 20, 20, 'r1'),
        ],
    }


def test_reg_index_yolo_nonames(regdir_var):
    """Region loading from YOLO-format files without .names mapping."""
    regdir_var.join('region.names').remove()
    regdir_var.join('index.csv').remove()
    path = str(regdir_var)
    ri = idx.reg_index(path)
    assert ri.region_types == ['0', '1', '2']  # Autogenerated.
    assert ri == {
        'white2.png': [
            (0, 0, 15, 45, '0'),
            (65, 70, 100, 100, '1'),
        ],
        'blue3.png': [
            (10, 10, 20, 20, '0'),
            (40, 10, 50, 20, '1'),
            (10, 30, 60, 90, '2'),
        ],
        'black.gif': [],
    }


def test_reg_index_pandas(regdir_pandas):
    """sth."""
    path = str(regdir_pandas)
    ri = idx.reg_index(path)
    assert ri.region_types == ['r1', 'r2', 'r3']
    assert ri == {
        'black.gif': [(10, 10, 20, 20, 'r1')],
        'blue3.png': [(10, 10, 20, 20, 'r2')],
        'white2.png': [(50, 50, 80, 90, 'r3')],
    }


def test_reg_index_2names(regdir_var):
    """2 .names files -> error."""
    regdir_var.join('other.names').write('foo\n')
    path = str(regdir_var)
    with pytest.raises(Exception) as info:
        idx.reg_index(path)
    assert str(info.value).startswith('Multiple .names files')


def test_reg_index_csvtxt(regdir_var):
    """Regions for the same image in both .csv and .txt files -> error."""
    regdir_var.join('index.csv').write('\n'.join([
        'image,xmin,ymin,xmax,ymax,label',
        'white2.png,10,10,10,10,r1',
    ]))
    path = str(regdir_var)
    with pytest.raises(Exception) as info:
        idx.reg_index(path)
    assert str(info.value).startswith('Regions specified twice')


def test_reg_index_nonames(regdir_var):
    """No .names file and regions in both .csv and .txt -> error."""
    regdir_var.join('region.names').remove()
    path = str(regdir_var)
    with pytest.raises(Exception) as info:
        idx.reg_index(path)
    assert str(info.value).startswith('A .names file is required')
