/// <reference path="../../node_modules/moment/moment.d.ts"/>
/// <reference path="../../node_modules/@types/jquery/index.d.ts"/>

// import moment = require("moment");

namespace DoctorSchedule {

    let recalculateDate = function (dateSpec, action) {
        dateSpec = parseDate(dateSpec);
        dateSpec.push((new Date).getFullYear());
        dateSpec = dateSpec.reverse();
        dateSpec[1]--;
        let momentDate = moment(dateSpec);
        momentDate[action](7, 'days');
        return momentDate.format('DD.MM');
    };

    let parseDate = function (string) {
        return string.split('.').map(data => parseInt(data));
    };

    let getDateColumn = function (row: JQuery) {
        return row.find('td:first-child');
    };

    let nextDate = function (prev: JQuery, next: JQuery) {
        getRows(next).each(function (index) {
            let date = getDateColumn($(this)).html();
            getDateColumn($(this)).html(recalculateDate(date, 'add'));
        });
        setButtonsText(prev, next, 'add');
    };

    let prevDate = function (prev: JQuery, next: JQuery) {
        getRows(next).each(function (index) {
            let date = getDateColumn($(this)).html();
            getDateColumn($(this)).html(recalculateDate(date, 'subtract'));
        });
        setButtonsText(prev, next, 'subtract');
    };

    let setButtonsText = function (prev: JQuery, next: JQuery, action) {
        setButtonDate(prev, action);
        setButtonDate(next, action);
    };

    let setButtonDate = function (button: JQuery, action) {
        let dates = button.html().trim().split(' – ');
        console.log(dates);
        button.html(recalculateDate(dates[0], action) + ' &ndash; ' + recalculateDate(dates[1], action));
    };

    let getRows = function (element: JQuery) {
        return element.parent().find('tr');
    };

    class DoctorSchedule {

        constructor(prevBtn, nextBtn) {
            let next = nextDate.bind(this);
            let prev = prevDate.bind(this);
            prevBtn.on('click', function (e) {
                e.preventDefault();
                prev(prevBtn, nextBtn);
            });
            nextBtn.on('click', function (e) {
                e.preventDefault();
                next(prevBtn, nextBtn);
            });
        }
    }


    export function init($prevBtn: JQuery, $nextBtn: JQuery) {
        return new DoctorSchedule($prevBtn, $nextBtn);
    }
}