var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http, $window, $parse) {


    angular.element("#price_range").slider({});



    $scope.objForm = {
        filial: null,
        modelo: null,
        marca: null,
        ano: null,
        max_price: null,
        min_price: null
    };

    $scope.arrModelos = [];
    $scope.arrFiliais = [];
    $scope.arrModelos = [];
    $scope.arrAnos = [];
    $scope.arrMarcas = [];


    $scope.$watch('objForm.marca', function (value) {
        if (value) {
            $scope.carregarFiltroModelos();
        }
    });

    $scope.setValue = function (campo, value) {

        if (value == null || value == "") {
            return;
        }

        var dados = 'objForm.' + campo;
        var model = $parse(dados);
        model.assign($scope, value);


    };

    $scope.calcularPreco = function () {

        preco = angular.element('#price_range').val();

        if (preco == "") {
            return;
        }

        $scope.objForm.min_price = preco.split(',')[0];
        $scope.objForm.max_price = preco.split(',')[1];


    };



    $scope.carregando_modelos = false;
    $scope.carregarFiltroModelos = function () {

        $scope.arrModelos = [];
        $scope.carregando_modelos = true;
        var url_base = '/wp-admin/admin-ajax.php?action=get_taxonomy_product&taxonomy=marca';

        url = url_base.concat('&term=' + $scope.objForm.marca);


        $http.get(url).then(
            function (response) {
                $scope.arrModelos = [];
                angular.forEach(response.data.posts, function (v, k) {

                    $scope.arrModelos.push({'slug': v.slug, 'name': v.name});
                })

            },
            function (error) {

            }
        ).finally(function (response) {
            $scope.carregando_modelos = false;
        });


    };

    $scope.filtrarVeiculos = function () {


        $scope.calcularPreco();

        var dados = $scope.serializeObj($scope.objForm);
        $window.location.href = '/estoque?' + dados;
    };


    $scope.filtrarVeiculosHome = function () {


        $scope.calcularPreco();


        var dados = $scope.serializeObj($scope.objForm);
        $window.location.href = '/estoque/?' + dados;

    };


    $scope.serializeObj = function (obj) {
        var result = [];
        for (var property in obj)

            if (obj[property] != null) {
                result.push(encodeURIComponent(property) + "=" + encodeURIComponent(obj[property]));
            }
        return result.join("&");
    }
});

app.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.myEnter);
                });

                event.preventDefault();
            }
        });
    };
});
