import io
import os
import re
import shutil
import unittest
from datetime import datetime
from orderedattrdict import AttrDict
from nose.tools import ok_
from . import folder
from gramex import variables
from gramex.install import init, _ensure_remove


class TestInit(unittest.TestCase):
    @classmethod
    def setUp(cls):
        cls.app_dir = os.path.join(folder, 'test-gramex-init')
        cls.cwd = os.getcwd()

    def test_init(self):
        if os.path.exists(self.app_dir):
            shutil.rmtree(self.app_dir, onerror=_ensure_remove)
        os.makedirs(self.app_dir)
        os.chdir(self.app_dir)
        init([], AttrDict())

        # Ensure files are present
        source = os.path.join(variables['GRAMEXPATH'], 'apps', 'init')
        for path in os.listdir(source):
            ok_(os.path.exists(os.path.join(self.app_dir, path)))

        # Ensure templates work
        with io.open(os.path.join(self.app_dir, 'gramex.yaml'), encoding='utf-8') as handle:
            line = handle.readline().strip()
            ok_('Please retain this line.' in line)
            today = datetime.now().strftime('%Y-%m-%d')
            expr = re.compile('Generated by gramex init on %s by .*? <.*>' % today)
            ok_(expr.search(line))

    @classmethod
    def tearDown(cls):
        os.chdir(cls.cwd)
        try:
            shutil.rmtree(cls.app_dir, onerror=_ensure_remove)
        except OSError:
            # Ideally, we should clean up the app_dir
            # But on Windows, npm / git may prevent this for some time. Ignore this
            pass
