# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#!/usr/bin/env python3
# -*- encoding=utf8 -*-
#
import glob
import unittest
import tempfile
import os
import subprocess
from ubunturecovery import recovery_common as common
from ubunturecovery import disksmgr

class UtilsTestCase(unittest.TestCase):

    def test_match_system_device(self):
        def _get(bus, argv):
            call = subprocess.Popen(argv, stdout=subprocess.PIPE)
            output = call.communicate()[0].decode('utf-8')
            line = output.split('\n')[0]
            if line:
                if bus == 'pci':
                    vendor = line.split(':')[2].strip()
                    product = line.split(':')[3].split()[0]
                elif bus == 'usb':
                    line = line.split(' ')[5]
                    (vendor, product) = line.split(':')
                return (vendor, product)
        (vendor, product) = _get('pci', ['lspci', '-n'])
        self.assertTrue(common.match_system_device('pci','0x' + vendor, '0x' + product))
        (vendor, product) = _get('usb',['lsusb'])
        self.assertTrue(common.match_system_device('usb','0x' + vendor, '0x' + product))

class SeedTestCase(unittest.TestCase):

    def setUp(self):
        self.filename = os.path.join(tempfile.gettempdir(), 'test.cfg')
        self._write([])

    def tearDown(self):
        os.remove(self.filename)

    def _read(self):
        return common.Seed(self.filename)

    def _write(self, lines):
        with open(self.filename, 'w') as fileobj:
            fileobj.write('\n'.join(lines + ['']))

    def test_parse(self):
        self._write([
            'd-i keyboard-configuration/layoutcode string us',
            'd-i keyboard-configuration/variantcode string',
            'd-i netcfg/dhcp_timeout string 5'
        ])
        seed = self._read()
        self.assertEqual(sorted([
            'keyboard-configuration/layoutcode',
            'keyboard-configuration/variantcode',
            'netcfg/dhcp_timeout'
        ]), sorted(seed.keys()))

    def test_set(self):
        self._write([
            'd-i keyboard-configuration/layoutcode string us',
            'd-i keyboard-configuration/variantcode string',
            'd-i netcfg/dhcp_timeout string 5'
        ])
        self.seed = self._read()
        self.seed.set('keyboard-configuration/layoutcode', 'tw')
        self.assertEqual('tw', self.seed.get('keyboard-configuration/layoutcode'))
        self.seed.set('new/layoutcode', 'tw')
        self.assertEqual('tw', self.seed.get('new/layoutcode'))

    def test_save(self):
        self.test_set()
        self.seed.save()
        new_seed = self._read()
        self.assertEqual(sorted({
            'keyboard-configuration/layoutcode':'tw',
            'keyboard-configuration/variantcode': '',
            'netcfg/dhcp_timeout':'5',
            'new/layoutcode':'tw'
        }), sorted(new_seed.keys()))

class DisksTestCase(unittest.TestCase):

    def test_didks(self):
        wantdevfd = sorted(glob.glob('/dev/sd*'))
        actdevfd = sorted([str(e.devicefile) for e in disksmgr.Udisks().devices()
                           if e.devicefile.startswith('/dev/sd')])
        self.assertEqual(wantdevfd, actdevfd)

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(UtilsTestCase, 'test'))
    suite.addTest(unittest.makeSuite(SeedTestCase, 'test'))
    suite.addTest(unittest.makeSuite(DisksTestCase, 'test'))
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='suite')
