# -*- coding: utf-8 -*-

import glob
import os

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files import File
from django.core.management.base import BaseCommand

from mtp.apps.documents.models import (
    Document
)
from mtp.apps.sync.models import Update
from mtp.apps.trainings.models import Training


class Command(BaseCommand):
    args = ''
    help = 'Import training from folder: .'

    def handle(self, *args, **options):
        #        from tendo import singleton
        #        me = singleton.SingleInstance()

        user_master = get_user_model().objects.get(username="mtp")

        update = Update()
        update.save()

        for path in args:
            print(path)
            training_name = os.path.basename(os.path.dirname(path))
            print("Formation %s" % (training_name))

            if not os.path.exists(path):
                print("%s does not exist" % (path))
                continue
            stag_folder = os.path.join(path, "STAGIAIRE")
            form_folder = os.path.join(path, "FORMATEUR")
            if not os.path.exists(stag_folder) or not os.path.exists(form_folder):
                print("%s is not a valid folder: STAGIAIRE and FORMATEUR folder need to be in" % path)  # noqa
                continue

            try:
                t = Training.objects.get(name=training_name)
            except:
                _image = File(open(os.path.join(settings.MEDIA_ROOT, "renault.png"), "r"))
                t_image = DownloadableFile(img=_image, order=0)
                t_image.save()
                t = Training(name=training_name, image=t_image)
                t.save()

            for f in glob.glob(os.path.join(stag_folder, '*.*')):
                if os.path.isfile(f):
                    print("Document stagiaire %s" % (f))
                    doc_file_comment = None
                    _file = File(open(f, 'r'))
                    doc_file = DocumentFile(orig_file=_file)
                    doc_file.save()
                    doc_master = Document(name=os.path.basename(f).rsplit('.', 1)[0])
                    doc_master.master = False
                    doc_master.trainer = False
                    doc_master.broadcastable = True
                    doc_master.user = user_master
                    doc_master.training = t
                    doc_master.doc_file = doc_file
                    doc_master.doc_file_comment = doc_file_comment
                    doc_master.save()

                    for user in get_user_model().objects.filter(is_staff=True):
                        if user == user_master:
                            continue
                        doc = Document(name=doc_master.name,
                                       doc_file=doc_file,
                                       doc_file_comment=doc_file_comment,
                                       training=t,
                                       user=user,
                                       master=True,
                                       trainer=doc_master.trainer,
                                       broadcastable=doc_master.broadcastable,
                                       hidden=doc_master.hidden,
                                       )
                        doc.save()

            for f in glob.glob(os.path.join(form_folder, '*.*')):
                if os.path.isfile(f):
                    print("Document formateur %s" % (f))

                    doc_file_comment = None
                    _file = File(open(f, 'r'))
                    doc_file = DocumentFile(orig_file=_file)
                    doc_file.save()
                    doc_master = Document(name=os.path.basename(f).rsplit('.', 1)[0])
                    doc_master.master = False
                    doc_master.trainer = True
                    doc_master.broadcastable = True
                    doc_master.user = user_master
                    doc_master.training = t
                    doc_master.doc_file = doc_file
                    doc_master.doc_file_comment = doc_file_comment
                    doc_master.save()

                    for user in get_user_model().objects.filter(is_staff=True):
                        if user == user_master:
                            continue
                        doc = Document(name=doc_master.name,
                                       doc_file=doc_file,
                                       doc_file_comment=doc_file_comment,
                                       training=t,
                                       user=user,
                                       master=True,
                                       trainer=doc_master.trainer,
                                       broadcastable=doc_master.broadcastable,
                                       hidden=doc_master.hidden,
                                       )
                        doc.save()
