'use strict';

angular
    .module('sloDialectsAdmin')
    .component('new', {
        templateUrl: 'components/new/new.template.html',
        controller: ['$http', '$routeParams', 'dialectSelect', '$location', '$scope', '$timeout', 'Config', function NewController($http, $routeParams, dialectSelect, $location, $scope, $timeout, Config) {

            var vm = this;
            vm.id = parseInt($routeParams.id);
            vm.selectItems = dialectSelect;
            vm.uploadFile = uploadFile;
            vm.createNewAnalysisItem = createNewAnalysisItem;
            vm.deleteAnalysisItem = deleteAnalysisItem;
            vm.save = save;
            vm.go = go;
            vm.cancel = cancel;
            vm.deleteAudio = deleteAudio;
            var audioPath;
            vm.analysisPlaceholders = [
                'Naglas', 'Dolgi samoglasniki', 'Kratki naglašeni samoglasniki', 'Nenaglašeni samoglasniki', 'Soglasniki', 'Oblikoslovni pojavi', 'Leksika'
            ];

            if(vm.id && vm.id > 0){
                getAllDialectData(vm.id);
            }

            function uploadFile(event){
                //document.getElementById('audio').classList.remove('hidden');

                //console.log(document.getElementById('selected'));
                document.getElementById('selected').classList.remove('hidden');
                document.getElementById('selected').innerText = document.getElementById('audio').value;
                var file = event.target.files[0];
                vm.fileFormData = new FormData();
                vm.fileFormData.append('file',file);
                file = null;
                /*
                 vm.dialectData.audioFile = file;
                 vm.dialectData.audio = file.name;
                 var files = document.getElementById('audio').files[0];

                 */
            };

            function getAllDialectData(id){
                getDialectData(id);
                getAnalysisData(id);
            }

            function getDialectData(id){
                $http.get('../api/dialects/'+id).then(function (result) {
                    vm.dialectData = result.data;
                    audioPath = Config.APP_PATH + vm.dialectData.audio;
                    if(vm.dialectData.audio){
                        var audio = document.createElement('AUDIO')
                        audio.id = 'audioID';
                        audio.controls = true;
                        audio.currentTime = 0;
                        document.getElementById('putAudio').appendChild(audio);
                        document.getElementById('audioID').src = audioPath;
                    }
                }, function (error) {
                    console.log('Error getting dialects');
                });
            }

            function getAnalysisData(id){
                $http.get('../api/dialects/'+id+'/analysis/').then(function (result) {
                    vm.analysisData = prepareAnalysisData(result.data);
                }, function (error) {
                    console.log('Error getting analysis');
                });
            }

            function prepareAnalysisData(analysis) {
                var _analysisData = [];
                analysis.forEach(function (a) {
                    _analysisData[a.section] = _analysisData[a.section] || [];
                    _analysisData[a.section].push({
                        id: a.id,
                        section: a.section,
                        maintext: a.maintext,
                        examples: a.examples
                    });
                });
                return _analysisData;
            }

            function createNewAnalysisItem(dialect_id, section_id){
                return $http.post('../api/dialects/'+dialect_id+'/analysis', {"section_id": section_id}).then(function(result){
                    // add also to view model
                    vm.analysisData = vm.analysisData || [];
                    vm.analysisData[section_id] = vm.analysisData[section_id] || [];
                    vm.analysisData[section_id].push({
                        id: result.data.id,
                        section: section_id,
                        maintext: '',
                        examples: ''
                    });
                    console.log('Successfuly created new analysis item.', result);
                }, function(error){
                    console.log('Error creating new analysis item.', error);
                });
            }

            function deleteAnalysisItem(dialect_id, analysis_id){
                if(confirm('Ali ste prepričani, da želite izbrisati ta vnos? ' + dialect_id + ' ' + analysis_id)){
                    $http.delete('../api/dialects/'+dialect_id+'/analysis/'+analysis_id).then(function(response){
                        // remove from view model
                        for(var i in vm.analysisData){
                            vm.analysisData[i] = _.filter(vm.analysisData[i], function(e){
                                return e.id != analysis_id;
                            });
                        }
                        console.log('Deleted analysis item with id', analysis_id + '. Response: ', response);
                    }, function(err){
                        console.log('Error deleting item ', analysis_id+':', err);
                    });
                }
            }

            function deleteAudio(delete_id, audio) {
                if(confirm('Ali ste prepričani, da želite izbrisati ta posnetek? ' + audio)){
                    if(delete_id && delete_id > 0){
                        document.getElementById('putAudio').removeChild(document.getElementById('putAudio').firstChild);
                        //console.log(delete_id);
                        var promise1 = $http.delete('../api/dialects/' + delete_id + '/audio', {

                        }).then(function(response){
                            getAllDialectData(delete_id);
                            //location.reload();
                            console.log('Datoteka je izbrisana.');
                        }, function(error){
                            alert('Prišlo je do napake pri brisanju.');
                            console.log('Error', error);
                        });
                    }
                }

            }

            function save(dialect_id, goBack){
                if(dialect_id && dialect_id > 0){
                    var promise1 = $http.put('../api/dialects/'+dialect_id, {
                        analysisData: vm.analysisData,
                        dialectData: vm.dialectData
                    }).then(function(response){
                        //alert('Narečje je bilo uspešno shranjeno.');
                    }, function(error){
                        alert('Prišlo je do napake pri shranjevanju.');
                        console.log('Error', error);
                    });

                    if(vm.fileFormData){
                        if(document.getElementById('putAudio').firstChild){
                            document.getElementById('putAudio').removeChild(document.getElementById('putAudio').firstChild);
                        }
                        var promise2 = $http({
                            method: 'POST',
                            url: '../api/dialects/'+vm.id+'/files',
                            data: vm.fileFormData,
                            headers: {'Content-Type': undefined, 'Process-Data': false},
                        }).then(function(response){
                            //console.log(response);
                            if(!goBack){
                                location.reload();
                                //console.log(response);
                            }

                            console.log('File uploaded.');
                        }, function(error){
                            console.log('Error uploading file:', error);
                        });

                        if(goBack){
                            Promise.all([promise1, promise2]).then(function() {
                                go('/');
                            });
                        } else {
                            Promise.all([promise1, promise2]).then(function() {
                                go('edit/'+vm.id);
                            });
                        }

                    } else {
                        if(goBack){
                            Promise.all([promise1]).then(function() {
                                go('/');
                            });
                        } else {
                            go('edit/'+vm.id);
                        }
                    }

                } else {
                    console.log('Dialect missing, cannot save.');
                }
            }

            function go(path){
                $location.path(path);
                $timeout(function() {
                    $scope.$apply();
                }, 0);

            }

            function cancel(path){
                if(confirm("Nov vnos se ne bo shranil, ali želite nadaljevati?")) {
                    $http.delete('../api/dialects/'+vm.id).then(function(result){
                        go(path);
                    }, function(error){
                        console.log('Error deleting entry:', error);
                    });
                }
            }

        }]
    });