var autoApp = angular.module('autoApp', ['ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.pagination', 'ui.grid.autoResize']);
autoApp.controller('AutoUsedController', ['$scope', '$http', '$interval', '$timeout', 'uiGridConstants', function ($scope, $http, $interval, $timeout, $uiGridConstants) {
    $scope.Message = "";
 
    var userAcct;
    var stockNumber;
    var userType;
    var userLogo;
 
    //GetUserAccount();
    function GetUserAccount() {
        //debugger;
        $http({
            method: 'Get',
            url: '/UsedCar/PassingUserAcct'
        }).success(function (data) {
            userAcct = data;
            $scope.userAccount = userAcct;
            GetUserInfo(userAcct);
            getPage(userAcct);
        }).error(function (data) {
            userAcct = '';
        });
    }
    userAcct="kc-3";
    var paginationOptions = {
        pageNumber: 1,
        pageSize: 25,
        sort: null
    };
 
    $scope.gridOptions = {
        enableRowSelection: true,
        enableRowHeaderSelection: false,
        enableColumnMenus: false,
        paginationPageSizes: [25, 50, 75],
        paginationPageSize: 25,
        useExternalPagination: true,
        useExternalSorting: true,
        columnDefs: [
          { field: 'ID', displayName: 'Item ID', width: 100, enableFiltering: false },
          { field: 'bodyType', displayName: 'Body Type', width: 100, height: 35, enableFiltering: false },
          { field: 'autoMake', displayName: 'Make', width: 150, height: 35 },
          { field: 'autoModel', displayName: 'Model', width: 150, height: 35 },
          { field: 'autoYear', displayName: 'Year', width: 60, height: 35 },
          { field: 'autoDoor', displayName: 'Doors', width: 60, height: 35, enableFiltering: false },
          { field: 'exteriorColor', displayName: 'Ext Color', width: 100, height: 35, enableFiltering: false },
          { field: 'interiorColor', displayName: 'Int Color', width: 100, height: 35, enableFiltering: false },
          { field: 'autoStatus', displayName: 'Status', width: 100, height: 35, cellClass: 'grid-align-center', enableFiltering: false },
          { field: 'salePrice', displayName: 'Price', width: 100, height: 35, cellFilter: 'currency', cellClass: 'grid-align-right', enableFiltering: false },
          { field: 'picture', displayName: 'Picture', width: 70, cellTemplate: "<img width=\"60px\" ng-src=\"{{grid.getCellValue(row, col)}}\" lazy-src>", enableFiltering: false },
          { field: 'Edit', width: 70, height: 35, cellTemplate: '<button class="btn primary" ng-click="grid.appScope.showDetail(row)">Edit</button>', enableFiltering: false }
        ],
 
        onRegisterApi: function (gridApi) {
            $scope.gridApi = gridApi;
            $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
                if (sortColumns.length === 0) {
                    paginationOptions.sort = null;
                } else {
                    paginationOptions.sort = sortColumns[0].sort.direction;
                }
                getPage(userAcct);
            });
            gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                paginationOptions.pageNumber = newPage;
                paginationOptions.pageSize = pageSize;
                getPage(userAcct);
            });
 
            $scope.gridOptions.multiSelect = false;
            $scope.gridOptions.modifierKeysToMultiSelect = false;
            $scope.gridOptions.noUnselect = true;
            $scope.gridOptions.onRegisterApi = function (gridApi) {
                $scope.gridApi = gridApi;
            };
 
            $scope.toggleRowSelection = function () {
                $scope.gridApi.selection.clearSelectedRows();
                $scope.gridOptions.enableRowSelection = !$scope.gridOptions.enableRowSelection;
                $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.OPTIONS);
            };
        }
    };
 
    var getPage = function (uAccount) {
         $http.get('http://localhost:4194/AutoService.svc/AutoUsedMaint/' + uAccount)
        //$http.get("/UsedCar/GetAutoUsed?userAccount=" + uAccount)
        .success(function (data) {
            $("#imgLoading").hide();
            var totalItems = data.length;
            $scope.gridOptions.totalItems = totalItems;
            var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
            $scope.gridOptions.data = data.slice(firstRow, firstRow + paginationOptions.pageSize);
        });
    };
 
        $scope.showDetail = function (row) {
            var vRecordId = row.entity.ID;
            $scope.stockNumber = row.entity.stockNumber
            $scope.userAccount = row.entity.accountNumber
            $scope.recordId = row.entity.ID
            $scope.bodyType = row.entity.bodyType
            $scope.autoMake = row.entity.autoMake
            $scope.autoModel = row.entity.autoModel
            $scope.autoYear = row.entity.autoYear
            $scope.exteriorColor = row.entity.exteriorColor
            $scope.interiorColor = row.entity.interiorColor
            $scope.autoEngine = row.entity.autoEngine
            $scope.autoDoor = row.entity.autoDoor
            $scope.autoMileage = row.entity.autoMileage
            $scope.salePrice = row.entity.salePrice
            $scope.newPrice = row.entity.newPrice
            $scope.autoStatu = row.entity.autoStatus
            $scope.userState = row.entity.userState
            $scope.userCity = row.entity.userCity
            $scope.imgDisplay = row.entity.picture
            $scope.notes = row.entity.notes
            $scope.VIN = row.entity.VIN
            if ($scope.imgDisplay === "") {
                $scope.imgDisplay = "http://23.111.184.175/BrandonAuto/images/autoBlankImage.png";
            }
        };
 
        function GetUserInfo(userAccount) {
            $http.get("http://localhost:4194/AutoService.svc/GetUserInfo/" + userAccount)
            .success(function (data, status, headers, config) {
                userType = data.AccountType;
                $scope.userInfo = data.DealerName;
                $scope.userLogo = data.Logo;
                if (userType === "Dealer") {
                    stockNumber = $scope.stockNumber;
                } else {
                    getStockNumber(userAccount);
                }
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
        }
 
    $scope.Reset = function () {
        if (userType === 'Indivisual') {
            getStockNumber(userAcct);
        } else {
            $scope.stockNumber = "";
        }
        $scope.bodyType = "";
        $scope.autoMake = "1";
        $scope.autoModel = "";
        $scope.autoYear = "";
        $scope.exteriorColor = "1";
        $scope.interiorColor = "1";
        $scope.autoEngine = "4";
        $scope.autoDoor = "2";
        $scope.autoMileage = "0";
        $scope.salePrice = "0";
        $scope.newPrice = "0";
        $scope.autoStatu = "0";
        $scope.userState = "1";
        $scope.userCity = "1";
        $scope.imgDisplay = "0";
        $scope.notes = "";
        $scope.VIN = "";
    };
 
    autoApp.filter('bodyType', function () {
        var genderHash = {
            1: 'Van',
            2: 'Truck',
            3: 'SUV',
            4: 'Wagons',
            5: 'Sedans',
            6: 'Any',
            7: 'Convetiples',
            8: 'Couples'
        };
        return function (input) {
            if (!input) {
                return 'this';
            } else {
                return "this is";  //genderHash[input];
            }
        };
    });
 
    function formatJSONDate(jsonDate) {
        var value = new Date(parseInt(jsonDate.replace(/(^.*\()|([+-].*$)/g, '')));
        var dat = value.getMonth() +
                                 1 +
                               "/" +
                   value.getDate() +
                               "/" +
               value.getFullYear();
        return dat;
    }
 
    $scope.getCellFormatDate = function (jsonDate) {
        //        $scope.dtFormated = dt | 'date:\'yyyy-MM-dd\'';
        var value = new Date(parseInt(jsonDate.replace(/(^.*\()|([+-].*$)/g, '')));
        var dtFormated = value.getMonth() +
                                 1 +
                               "/" +
                   value.getDate() +
                               "/" +
               value.getFullYear();
        return dtFormated;
    };
 
    $scope.showImage = function (image) {
        var value = row.entity.picture;
        return value;
    };
 
    $scope.newPrice = "0";
    $scope.autoStatu = "0";
 
    //Pad given value to the left with "0"
    function AddZero(num) {
        return (num >= 0 && num < 10) ? "0" + num : num + "";
    }
 
    function getStockNumber(vUserAcct) {
        //debugger;
        var now = new Date();
        var DD = AddZero(now.getDate());
        var MM = AddZero(now.getMonth());
        var YY = AddZero(now.getYear());
 
        $http({
            method: 'Get',
            url: 'UsedCar/GetNextStockNumber/',
            data: JSON.stringify(vUserAcct),
            dataType: "json"
        }).success(function (data) {
            $scope.stockNumber = vUserAcct + DD.toString() + "-" + MM.toString() + "-" + YY.toString();
        }).error(function (data) {
            stockNumber = '';
        });
    }
 
    $scope.AddAutoUsed = function () {
        var autoUsed = {
            stockNumber: $scope.stockNumber,
            accountNumber: $scope.userAccount,
            bodyType: $scope.bodyType,
            autoYear: $scope.autoYear,
            autoMake: $scope.autoMake,
            autoModel: $scope.autoModel,
            exteriorColor: $scope.exteriorColor,
            interiorColor: $scope.interiorColor,
            autoEngine: $scope.autoEngine,
            autoDoor: $scope.autoDoor,
            autoMileage: $scope.autoMileage,
            salePrice: Number($scope.salePrice.toString().replace(/[^0-9\.-]+/g, "")),
            newPrice: Number($scope.newPrice.toString().replace(/[^0-9\.-]+/g, "")),
            autoStatus: $scope.autoStatu,
            banner: 0,
            userState: $scope.userState,
            userCity: $scope.userCity,
            picture: "",  //autoBidImagePath + "/" + $scope.recordId + '/' + $scope.picture.trim()
            notes: $scope.notes,
            VIN: $scope.VIN
        };
        // Add Auto
        var response = $http({
            method: "post",
            url: "UsedCar/AddAutoUsed",
            data: JSON.stringify(autoUsed),
            dataType: "json"
        }).success(function (data) {
            refresh(userAcct);
            $scope.Message = "New Auto Added Successfuly";
        }).error(function (data) {
            $scope.Message = "Unexpected error";
        });
    };
 
    $scope.UpdateAutoUsed = function () {
        var autoUsed = {
            ID: $scope.recordId,
            stockNumber: $scope.stockNumber,
            bodyType: $scope.bodyType,
            autoYear: $scope.autoYear,
            autoMake: $scope.autoMake,
            autoModel: $scope.autoModel,
            exteriorColor: $scope.exteriorColor,
            interiorColor: $scope.interiorColor,
            autoEngine: $scope.autoEngine,
            autoDoor: $scope.autoDoor,
            autoMileage: $scope.autoMileage,
            salePrice: Number($scope.salePrice.toString().replace(/[^0-9\.-]+/g, "")),
            newPrice: Number($scope.newPrice.toString().replace(/[^0-9\.-]+/g, "")),
            autoStatus: $scope.autoStatu,
            userState: $scope.userState,
            userCity: $scope.userCity,
            notes: $scope.notes,
            VIN: $scope.VIN
        };
        var response = $http({
            method: "post",
            url: "UsedCar/UpdateAutoUsed",
            data: JSON.stringify(autoUsed),
            dataType: "json"
        }).success(function (newData) {
            refresh(userAcct);
            $scope.Message = "Auto Updated Successfuly";
        }).error(function (data) {
            $scope.Message = "Unexpected error";
        });
    };
 
    $scope.deleteAutoUsed = function (autoUsed) {
        //var autoUsed = {
        //    ID: $scope.recordId
        //}
        if (confirm("Are you sure to delete " + $scope.stockNo + "?")) {
            var response = $http({
                method: "post",
                url: "UsedCar/DeleteAutoUsed",
                data: JSON.stringify(autoUsed),
                dataType: "json"
            }).success(function (newData) {
                deleteImageFile();
                $scope.Message = "Auto Updated Successfuly";
            }).error(function (data) {
                $scope.Message = "Unexpected error";
            });
        }
    };
    function deleteImageFile() {
//        debugger;
        var recordId = $scope.recordId;
        var imageName = $scope.imgDisplay;
        if (recordId) {
            $http({
                method: 'POST',
                url: 'UsedCar/DeletePhoto',
                data: JSON.stringify({ id: recordId, fileName: imageName })
            }).success(function (data, status, headers, config) {
                refresh(userAcct);
                $scope.Message = "Auto Deleted Successfuly";
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
        }
        else {
            $scope.autoModel = null;
        }
    }
 
    GetAutoMakes();
    function GetAutoMakes() {
        $http.get("http://localhost:4194/AutoService.svc/GetAutoMake/")
            .success(function (data, status, headers, config) {
                $scope.autoMakes = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    $scope.GetAutoModels = function () {
        var makeId = $scope.autoMake;
        $http.get("http://localhost:4194/AutoService.svc/GetAutoModels/" + makeId)
            .success(function (data, status, headers, config) {
                $scope.autoModels = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    function GetEditModel() {
        $http({
            method: 'Get',
            url: 'UsedCar/GetAutoMakes'
        }).success(function (data, status, headers, config) {
            $scope.autoMakes = data;
        }).error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error';
        });
    }
 
    GetAutoYears();
    function GetAutoYears() {
        $http.get("http://localhost:4194/AutoService.svc/GetYears/")
            .success(function (data, status, headers, config) {
                $scope.autoYears = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    EngineList();
    function EngineList() {
        $http.get("http://localhost:4194/AutoService.svc/GetAutoEngine/")
            .success(function (data, status, headers, config) {
                $scope.autoEngines = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    BodyTypeList();
    function BodyTypeList() {
        $http.get("http://localhost:4194/AutoService.svc/GetBodyType/")
            .success(function (data, status, headers, config) {
                $scope.autoBodyType = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    ColorList();
    function ColorList() {
        $http.get("http://localhost:4194/AutoService.svc/GetAutoColor/")
            .success(function (data, status, headers, config) {
                $scope.autoColors = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    AutoStatusList();
    function AutoStatusList() {
        $http.get("http://localhost:4194/AutoService.svc/GetAutoStatus/")
            .success(function (data, status, headers, config) {
                $scope.autoStatus = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    AutoDoorList();
    function AutoDoorList() {
        $http.get("http://localhost:4194/AutoService.svc/GetAutoDoor/")
            .success(function (data, status, headers, config) {
                $scope.autoDoors = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    $scope.UploadFile = function (file) {
        var files = file[0];
        $scope.Imagename = files.name;
        $scope.SelectedFileForUpload = file[0];
 
        var response = $http({
            method: "post",
            url: "UsedCar/UploadFiles",
            data: file,
            dataType: "json"
        });
        return response;
    };
 
    //Save File
    $scope.SaveFile = function () {
        $scope.IsFormSubmitted = true;
        $scope.Message = "";
        $scope.ChechFileValid($scope.SelectedFileForUpload);
        if ($scope.IsFormValid && $scope.IsFileValid) {
            FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {
                var autoBidDetails = {
                    ID: $scope.recordId,
                    picture: $scope.picture
                };
            });
        }
    };
 
    $scope.SaveImage = function () {
        var autoBid = {
            ID: $scope.recordId,
            picture: autoBidImagePath + "/" + $scope.recordId + '/' + $scope.picture.trim()
        };
        $scope.IsFormSubmitted = false;
        // Update Image
        var response = $http({
            method: "post",
            url: "UsedCar/UploadFiles",
            data: JSON.stringify(autoBid),
            dataType: "json"
        });
        return response;
    };
 
    GetStates();
    function GetStates() {
        $http({
            method: 'Get',
            url: 'http://localhost:4194/AutoService.svc/GetState/'
        }).success(function (data) {
            $scope.States = data;
        }).error(function (data) {
            $scope.Message = 'Get State Unexpected Error';
        });
    }
 
    var stateId;
    $scope.GetCities = function () {
        stateId = $scope.userState;
        if (stateId) {
            $http.get("http://localhost:4194/AutoService.svc/GetCity/" + stateId)
                .success(function (data, status, headers, config) {
                    $scope.Cities = data;
                }).error(function (data, status, headers, config) {
                    $scope.Message = 'Get Cities Unexpected Error';
                });
        }
        else {
            $scope.custCity = null;
        }
    };
 
    SaleStatusList();
    function SaleStatusList() {
        $http.get("http://localhost:4194/AutoService.svc/SaleStatus")
            .success(function (data, status, headers, config) {
                $scope.SaleStatus = data;
            }).error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    }
 
    function refresh(uAccount) {
        //        $http.get("http://localhost:4194/AutoService.svc/AutoUsedMaint/" + uAccount)
        $http.get("UsedCar/GetAutoUsed?userAccount=" + uAccount)
        .success(function (newdata) {
            $scope.gridOptions.data.length = 0;
            $scope.gridOptions.data = [];
            $timeout(function () {
                $scope.gridOptions.data = newdata;
           });
        });
    };
}
]);
 
// allow you to format a text input field.
// <input type="text" ng-model="test" format="number" />
// <input type="text" ng-model="test" format="currency" />
autoApp.directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;
 
            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue);
            });
 
            elem.bind('blur', function (event) {
                var plainNumber = elem.val().replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
            });
        }
    };
}]);