# -*- coding: utf-8 -*-
"""Server play-log tombstones delete only the named row and are idempotent (MCP library/history support)."""
import os
import sys
import unittest
from unittest import mock

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), 'library_harness'))
import stubs  # noqa: E402
PROFILE = stubs.install()
from wcs.account import apply  # noqa: E402
from wcs.library2 import store  # noqa: E402


class PlayLogDeleteTests(unittest.TestCase):
    def setUp(self):
        store.set_path(os.path.join(PROFILE, 'play-log-delete.db'))
        with store.tx() as conn:
            conn.execute('DELETE FROM play_log')

    def test_named_delete_replay_and_recent_row_invalidation(self):
        row = {'media_type': 'tv', 'tmdb_id': 1480, 'season': 1, 'episode': 2,
               'started_at': 100, 'ended_at': 200, 'position': 300, 'total': 2500, 'outcome': 'stopped'}
        with store.tx() as conn:
            self.assertTrue(apply._play_log(conn, store, 'first', row, False))
            self.assertTrue(apply._play_log(conn, store, 'keep', row, False))
            with mock.patch.object(store, 'dirty') as dirty:
                self.assertTrue(apply._play_log(conn, store, 'first', {}, True))
                dirty.assert_called_once_with(conn, {'recent_played'})
                self.assertFalse(apply._play_log(conn, store, 'first', {}, True))
                dirty.assert_called_once()
            self.assertIsNone(conn.execute('SELECT 1 FROM play_log WHERE uuid=?', ('first',)).fetchone())
            self.assertIsNotNone(conn.execute('SELECT 1 FROM play_log WHERE uuid=?', ('keep',)).fetchone())


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