# coding: utf-8
from __future__ import unicode_literals, absolute_import

from datetime import datetime

import openpyxl
from django.core.management.base import BaseCommand
from django.db import transaction

from fb.feedback.models import Feedback, FeedbackGroup
from fb.staff.models import Person


def _parse_file(filepath):
    """ returns dict, key=login, value=fb_text """
    with open(filepath) as fh:
        wb = openpyxl.load_workbook(fh)
        sheet = wb.get_sheet_by_name('feedbacks')
        res = {}
        for row in sheet.values:
            if len(row) <2 or not all(isinstance(it, basestring) for it in row[:2]):
                continue
            login, fb = row[0], row[1]
            res[login] = fb
    return res


@transaction.atomic
def handle(filepath, fb_date):
    login_to_fb = _parse_file(filepath)
    login_to_person = {
        p.login: p
        for p in Person.objects.filter(login__in=login_to_fb)
    }
    for login, fb_text in login_to_fb.items():
        person = login_to_person.get(login)
        if not person:
            print 'No person {}'.format(login)
            continue
        fb = Feedback.objects.create(
            reporter=person,
            reporter_type=Feedback.RT_SELF,
            positive_message=fb_text,
        )
        fb.create_time = fb_date
        fb.save()
        FeedbackGroup.objects.create(
            feedback=fb,
            person=person,
        )


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('filepath', type=str)
        parser.add_argument('fb_date', type=str)

    def handle(self, *args, **options):
        filepath = options['filepath']
        fb_date = datetime(*options['fb_date'].split('-'))

        try:
            with open(filepath, 'r'):
                pass
        except Exception as exc:
            print('Please provide a valid file path: {}'.format(exc))
            return

        handle(filepath, fb_date)
