'use strict';

var app =angular.module('BlurAdmin', [
  'ngAnimate',
  'ui.bootstrap',
  'bootstrap.fileField',
  'angularUtils.directives.dirPagination',
  'ui.sortable',
  'ui.router',
  'ngTouch',
  'toastr',
  'smart-table',
  'xeditable',
  'ui.slimscroll',
  'ngJsTree',
  'ngCookies',
  'angular-progress-button-styles',
  'BlurAdmin.theme',
  'BlurAdmin.pages'
])
    .constant('domain','http://backend.flexoli.com/public')
    .constant('api','/api/admin/v1_0/')
.constant('token','tokenSessionAdmin')
.service('urls',function(domain,api, token){ this.apiUrl = domain+api; this.baseUrl = domain; this.tokenSession = token});
app.controller('MainCtrl', function($cookies, $scope, $filter, $http, $state, urls) {
    $scope.baseUrl = urls.baseUrl;
    $scope.url     = urls.apiUrl;
    $scope.token   = urls.tokenSession;
    $scope.itemsBypage = 10;
       $scope.pagination = {
        currentProduct: 1
    };
    $scope.pagination = {
        currentVariante: 1
    };
    $scope.pagination = {
        currentRemise: 1
    };
    $scope.pagination = {
        currentSsFamille: 1
    };
    $scope.pagination = {
        currentFamille: 1
    };
    $scope.pagination = {
        currentParticulier: 1
    };
    $scope.pagination = {
        currentRevendeurs: 1
    };
    $scope.pagination = {
        current: 1
    };
    // Put coockie
    $scope.putCoockie = function (key , value) {
        $cookies.put(key, value);
    };
    // Get coockie
    $scope.getCoockie = function (key) {
        return  $cookies.get(key);
    };
    // Remove coockie
    $scope.removeCoockieUser = function () {
        $cookies.remove('tokenSessionAdmin');
        window.location.replace('#/login');
    };
    $scope.isLogged = function () {
        if ($scope.getCoockie('tokenSessionAdmin') != null )
            return true;
        else
            return false;
    };
    $scope.userSession = function() {
        return $scope.getCoockie('tokenSessionAdmin');
    };
    $scope.convertToPriceFormat= function(val) {
        return parseFloat(val.replace(",", "."));
    }
    $scope.convertToPriceFormatWithVirgul= function(val) {
        return val.replace(".", ",");
    }
    $scope.sleep = function (milliseconds) {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > milliseconds){
                break;
            }
        }
    }
    // return error message
    $scope.getErrorMessage = function (response) {
        var responseError = '';
    
        if(response.data != null) {
            if(response.data.hasOwnProperty('message'))
                responseError = response.data.message;
            else if(response.data.hasOwnProperty('messages'))
                responseError = response.data.messages[0];
            else
                responseError = "Une erreur s'est produite, merci de réessayer.";
        } else {
            responseError = "Une erreur s'est produite, merci de réessayer.";
        }


        return responseError;
    }
    $scope.getErrorMessageAPI = function (response) {
        var responseError = '';

        if(response != null) {
            if(response.hasOwnProperty('message'))
                responseError = response.message;
            else if(response.hasOwnProperty('messages'))
                responseError = response.messages[0];
            else
                responseError = "Une erreur s'est produite, merci de réessayer.";
        } else {
            responseError = "Une erreur s'est produite, merci de réessayer.";
        }


        return responseError;
    }

    $scope.booleanToInteger = function (val) {
        if (val)
            return 1;
        else
            return 0;
    };
        $scope.integerToBoolean = function (val) {
        if (val==1)
            return true;
        else
            return false;
    };
    // Hide message
    $scope.hideMsg = function () {
        $('#msgTop').hide();
        $('#msgBottom').hide();


    }
    $scope.hideMsgBottom = function () {
        $('#msgBottom').hide();
    }
    $scope.hideMsgError = function () {
        $('#msgError').hide();
    }
    // Get categorie by ID
    $scope.getCategoryByID = function (id_category) {

        var url = $scope.baseUrl+"/Flexoli/BackEnd/public//api/admin/v1_0/categories/"+id_category;
        $http({
            method: 'GET',
            url: url,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization" : $scope.userSession()
            }
        }).then(function successCallback(response) {
            if(response.status == 200) {
               return $scope.category = response.data;
            } else
               return  $scope.response_error = "Une erreur s'est produite, merci de réessayer.";

        }, function errorCallback(response) {
           return $scope.response_error = response.data.message;
        });
    }
    // Get by position on array
    $scope.getByPosition = function (input, pos) {

        var i=0, len=input.length;
        for (; i<len; i++) {
            if (i == pos) {
                return input[i];
            }
        }
        return null;
    }
    $scope.setFile = function(element) {
        $scope.$apply(function($scope) {
            $scope.theFile = element.files[0];
        });
    };
    // Get statuses
    $scope.getStatuses = function () {

        var url = $scope.baseUrl+"/api/admin/v1_0/statuses";
        $http({
            method: 'GET',
            url: url,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization" : $scope.userSession()
            }
        }).then(function successCallback(response) {
            if(response.status == 200)
                $scope.statuses = response.data;
            else
                $scope.reror_status = "Une erreur s'est produite, merci de réessayer.";

        }, function errorCallback(response) {
            $scope.reror_status = "Une erreur s'est produite, merci de réessayer.";
        });
    }
    if($scope.isLogged())
        $scope.getStatuses();

	$scope.frenchDateTimeFormat = function (date) {
        return $filter('frenchDateTime')(date);
    }
    
    $scope.frenchDateTimeFormat = function (date) {
        return $filter('frenchDateTime')(date);
    }
    $scope.frenchDateFormat = function (date) {
        if (date == null) return '';
        return $filter('frenchDate')(date);
    }
    $scope.simpleDateFormat = function (date) {
        if(date !=null)
           return $filter('simpleDate')(date);
       else
           return null;
    }
      $scope.convertDateFormat = function (date) {
        return $filter('formatedDate')(date);
    }

    // Check access
    $scope.checkAccessUser = function () {

        var url = $scope.baseUrl+"/Flexoli/BackEnd/public//api/admin/v1_0/checkAccess";
        $http({
            method: 'GET',
            url: url,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization" : $scope.userSession()
            }
        }).then(function successCallback(response) {
            if(response.status == 200)
                 return true;
             else
                return false;

        }, function errorCallback(response) {
               return false;
        });
    }
})

app.filter('getByPosition', function() {
    return function(input, pos) {
        var i=0, len=input.length;
        for (; i<len; i++) {
            if (i == pos) {
                return input[i];
            }
        }
        return null;
    }
});
app.filter('frenchDateTime', function(dateFilter) {
    var formattedDate = '';
    return function(dt) {
        formattedDate = dateFilter(new Date(dt), 'dd-MM-yyyy HH:mm:ss');
        return formattedDate;
    }
});

app.filter('frenchDate', function(dateFilter) {
    var formattedDate = '';
    return function(dt) {
        formattedDate = dateFilter(new Date(dt), 'dd-MM-yyyy');
        return formattedDate;
    }
});

app.filter('formatDate', function(dateFilter) {
    var formattedDate = '';
    return function(dt) {
        formattedDate = dateFilter(new Date(dt.split('-')), 'yyyy-M-d');
        return formattedDate;
    }

});
app.filter('formatedDate', function(dateFilter) {
    var formattedDate = '';
    return function(dt) {
        //formattedDate = dateFilter(new Date(dt.split('-')), 'yyyy-M-d');
        var d=dt.split('-');
        var t=d[2].split(' ');
        formattedDate=d[0]+"-"+d[1]+"-"+t[0];
        return formattedDate;
    }

});
app.filter('simpleDate', function(dateFilter) {
    var formattedDate = '';
    return function(dt) {
        formattedDate = dateFilter(new Date(dt), 'yyyy-M-d');
        return formattedDate;
    }

});
app.directive('validPasswordC', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {

            ctrl.$setValidity('noMatch', true);

            attrs.$observe('validPasswordC', function (newVal) {
                if (newVal === 'true') {
                    ctrl.$setValidity('noMatch', true);
                } else {
                    ctrl.$setValidity('noMatch', false);
                }
            });
        }
    }
});
app.directive("filesInput", function() {
    return {
        require: "ngModel",
        link: function postLink(scope,elem,attrs,ngModel) {
            elem.on("change", function(e) {
                var files = elem[0].files;
                console.log('images',files)
                ngModel.$setViewValue(files);
            })
        }
    }
});
app.factory("factoryAPI", function($http){
    return {
        callGETService: function(url, session){

            return $http({
                url: url,
                method: 'GET',
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Authorization" : session
                }
            });

        },
        callPOSTService: function(url, session, params){

            return $http({
                url: url,
                method: 'POST',
                data: $.param(params),
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Authorization" : session
                }
            });
        }
        ,
        callPUTService: function(url, session, params){

            return $http({
                url: url,
                method: 'PUT',
                data: $.param(params),
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Authorization" : session
                }
            });
        }
        }
});
