angular.module('CustomTrackerFormDirective', ['BiometricApi', 'TimeFactory'])

    .directive('customTrackerForm', function (FOLDER_PATHS) {
        return {
            restrict: 'EA',
            templateUrl: FOLDER_PATHS.biometricTrackers + 'directives/tracker-form.html',
            scope: {
                tracker: '=',
                hasDate: '=?',
                hasTime: '=?',
                savedNow: '=?',
                fields: '=',
                initData: '=?',
                saveGuids: '=?',
                skippable: '=?',
                doneCb: '&'
            },
            link: function (scope, ele, $attrs) {
                if (scope.hasDate === undefined) {
                    scope.hasDate = true;
                }
                if (scope.hasTime === undefined) {
                    scope.hasTime = false;
                }
                if (!scope.fields || !scope.fields.length) {
                    scope.fields = [];
                }
            },
            controller: function ($scope, timeFactory, $biometricApi, $userApi) {
                $scope.formModel = {};
                $scope.editingRecord = false;
                $scope.recordProcessing = false;
                $scope.maxDate = moment().startOf('day').format('M/D/YYYY');
                $scope.specificValidationError = "";
                $scope.units = "";
                $scope.unitLabel = "";

                $userApi.getUserMeasurementSystem()
                    .then(function (res) {
                        if (res) {
                            $scope.units = res;
                        }

                        if ($scope.initData) {
                            //console.log($scope.initData)
                            $scope.formModel.entryDate = timeFactory.agnosticDateConvert($scope.initData.entryDate, $scope.initData.tzOffset, "M/D/YYYY");
                            $scope.formModel.entryTime = timeFactory.agnosticTimeConvertBio($scope.initData.entryDate, $scope.initData.tzOffset);
                            var validDataFields = ['entry'];
                            for (var i = 0; i < validDataFields.length; i++) {
                                var field = validDataFields[i];
                                $scope.initData[field] ? $scope.formModel[field] = $scope.initData[field] : '';

                                if ($scope.initData[field]) {
                                    switch ($scope.tracker.id) {
                                        case 1040:
                                            $scope.formModel[field] = $biometricApi.convertValueDisplay('weight', $scope.initData[field], $scope.units)
                                            break;
                                        case 1041:
                                            $scope.formModel[field] = $biometricApi.convertValueDisplay('bloodglucose', $scope.initData[field], $scope.units)
                                            break;
                                        case 2001:
                                            $scope.formModel[field] = $biometricApi.convertValueDisplay('minutes', $scope.initData[field], null)
                                            break;
                                        case 2011:
                                            $scope.formModel[field] = $biometricApi.convertValueDisplay('inches', $scope.initData[field], $scope.units)
                                            break;
                                    }
                                }
                            }
                        } else {
                            $scope.formModel.entryDate = timeFactory.agnosticDateConvert(moment(), moment().utcOffset(), "M/D/YYYY");
                            $scope.formModel.entryTime = timeFactory.agnosticTimeConvertBio(moment(), moment().utcOffset());
                        }
                    })

                setTimeout(function () {
                    var fInput = $('.data-focus-on input')[0];
                    if (fInput) {
                        fInput.focus();
                    }
                }, 100)

                $scope.formProcessing = function () {
                    $scope.specificValidationError = "";
                    if (!$scope.trackerForm.$valid) {
                        $("form[name = 'trackerForm']").find('.ng-invalid:first').focus();
                        return;
                    }
                    if (moment().endOf('day').diff($scope.formModel.entryDate, 'days') < 0) {
                        $scope.specificValidationError = "Entry date can not be in future.";
                        $("form[name = 'trackerForm']").find('.date.form-control').focus();
                        return;
                    }

                    var newRecord = {};
                    if ($scope.hasDate || $scope.savedNow) {
                        var saveTime = $scope.formModel.entryTime;
                        if (saveTime.indexOf('PM') > -1 || saveTime.indexOf('AM') > -1) {
                            //loaded time entry has am/pm when not changed
                            fixedTime = moment($scope.formModel.entryTime, "h:mm A").format("HH:mm:ss");
                            newRecord.entryDate = timeFactory.localDateTimeToUtc($scope.formModel.entryDate, fixedTime);
                        } else {
                            //normal
                            newRecord.entryDate = timeFactory.localDateTimeToUtc($scope.formModel.entryDate, $scope.formModel.entryTime);
                        }
                    }
                    $scope.fields.forEach(function (field) {
                        newRecord[field.dataApi] = $scope.formModel[field.dataApi];
                        switch ($scope.tracker.id) {
                            case 1040:
                                newRecord[field.dataApi] = $biometricApi.convertValueApi('weight', newRecord[field.dataApi], $scope.units)
                                break;
                            case 1041:
                                newRecord[field.dataApi] = $biometricApi.convertValueApi('bloodglucose', newRecord[field.dataApi], $scope.units)
                                break;
                            case 2001:
                                newRecord[field.dataApi] = $biometricApi.convertValueApi('minutes', newRecord[field.dataApi], null)
                                break;
                            case 2011:
                                newRecord[field.dataApi] = $biometricApi.convertValueApi('inches', newRecord[field.dataApi], $scope.units)
                                break;
                        }
                    })

                    if ($scope.initData) {
                        return $scope.updateRecord(newRecord)
                    } else {
                        return $scope.submitNewRecord(newRecord)
                    }
                }

                $scope.submitNewRecord = function (record) {
                    $scope.recordProcessing = true;
                    record.trackerid = $scope.tracker.id;
                    return $biometricApi.createCustomRecord($scope.tracker.id, record, $scope.saveGuids)
                        .then(processRecordApiResponse)
                }

                $scope.updateRecord = function (record) {
                    $scope.recordProcessing = true;
                    record.trackerid = $scope.tracker.id;
                    return $biometricApi.updateCustomRecord($scope.tracker.id, $scope.initData.id, record)
                        .then(processRecordApiResponse)
                }

                function processRecordApiResponse(res) {
                    $scope.recordProcessing = false;
                    if (res) {
                        $scope.closeForm(true);
                    }
                }

                $scope.onlyUnfilledDates = function (date) {
                    if ($scope.editingRecord) {
                        //user should be able to reselect same date if they changed it
                        if (timeFactory.utcToLocal(date) === timeFactory.utcToLocal($scope.originalDate)) {
                            return false;
                        }
                    }
                    if (!$scope.records || !$scope.records.length) {
                        return false;
                    }
                    for (var i = 0; i < $scope.records.length; i++) {
                        var entryDate = $scope.records[i].entryDate;
                        //console.log(timeFactory.utcToLocal(date) + ' vs ' + timeFactory.utcToLocal(entryDate))
                        if (timeFactory.utcToLocal(date) === timeFactory.utcToLocal(entryDate)) {
                            return true;
                        }
                    }
                    return false;
                }

                $scope.formSubmitType = function () {
                    if ($scope.initData) {
                        return "Save";
                    } else {
                        return "Add";
                    }
                }

                $scope.closeForm = function (refresh) {
                    $scope.doneCb({ refreshGraph: refresh });
                }
                $scope.skipForm = function () {
                    $scope.doneCb();
                }
            }
        }
    })
