var titolareController = function (
	editAndUploadModalFactory,
	utilsFactory,
	gettextCatalog,
	modalFactory,
	mainConstants,
	archiveComponentFactory,
	errorConstants,
	sessionFactory,
	errorFactory,
	titolareFactory
) {
	var ctrl = this;

	ctrl.$onInit = function () {
		initVars();
		if (!ctrl.customers)
			ctrl.getCustomers();
		else if (!ctrl.forceOwnerEmpty)
			ctrl.setSelectedOwner();
	};

	function initVars() {
		ctrl.newDocumentOwner = {
			personalDetails: {
				name: null,
				lastName: null
			},
			businessName: null,
			fiscalCode: null,
			vatCode: null
		}

		if (!ctrl.selectedOwner)
			ctrl.selectedOwner = {};

		ctrl.previousOwnerValue = ctrl.selectedOwner

		if (ctrl.contribuente){
			ctrl.originalContribuente = ctrl.contribuente
			ctrl.editedContribuente = ctrl.contribuente
			ctrl.showContribuente = true
		}

		ctrl.currentUser = sessionFactory.getCurrentUser();
		ctrl.disableCFAndVat = false
		ctrl.disableNameFields = true

		ctrl.autoSearchTimer = null

		ctrl.validations = {}
		ctrl.validations.vatCodeValidation = {
			validate: function (value) {
				if (utilsFactory.isBlank(value)) {
					ctrl.validations.vatCodeValidation.status = "NO_ERROR"
					return
				}
				utilsFactory.validateVatCode(value, ctrl.validations.vatCodeValidation, true)
			},
			status: "NO_ERROR",
			errors: {
				"NO_ERROR": "",
				"NOT_VALID_LENGTH": gettextCatalog.getString('blc-validation-not-valid-length-vat'),
				"NOT_VALID": gettextCatalog.getString('blc-validation-not-valid-semantic-vat')
			}
		};

		ctrl.validations.fiscalCodeValidation = {
			validate: function (value) {
				utilsFactory.validateFiscalCode(value, ctrl.validations.fiscalCodeValidation)
			},
			status: "NO_ERROR",
			errors: {
				"NO_ERROR": "",
				"NOT_VALID_LENGTH": "Lunghezza non valida.",
				/* "NOT_VALID_REG_EXP_VAT_FISCAL_3": gettextCatalog.getString('blc-not-valid-regexp-vat-fiscal_3'), */
				"NOT_VALID": gettextCatalog.getString('blc-validation-not-valid-semantic-cf')

			}
		};
	}

	ctrl.restoreSelectedOwner = function () {
		if(ctrl.contribuente){
			ctrl.editedContribuente = ctrl.originalContribuente
			ctrl.onOwnerUdate({ selectedOwner: null, newDocumentOwner: null, validations: {}, contribuente: ctrl.originalContribuente })
		}
		if (ctrl.previousOwnerValue.id)
			ctrl.selectedOwnerUpdate(ctrl.previousOwnerValue)
		else
			ctrl.setSelectedOwner()
		if (ctrl.contribuente)
			ctrl.showContribuente = true

		ctrl.disableCFAndVat = true
		ctrl.disableNameFields = true
	}

	ctrl.setSelectedOwner = function () {
		if (ctrl.selectedOwner && ctrl.selectedOwner.id) {
			ctrl.selectedOwnerUpdate(ctrl.selectedOwner)
		}
		else {
			if (ctrl.formInfo) {
				ctrl.selectedOwner = ctrl.formInfo.customers.find(function (owner) {
					return owner.id === ctrl.currentUser.company.owner.id
				})
			} else {
				ctrl.selectedOwner = ctrl.customers.find(function (owner) {
					return owner.id === ctrl.currentUser.company.owner.id
				})
			}
			ctrl.selectedOwnerUpdate(ctrl.selectedOwner)
		}
		ctrl.onFormChange()
	}

	ctrl.getCustomers = function () {
		var successCallback = function (response) {

			ctrl.formInfo = response.formInfo;
			ctrl.customers = ctrl.formInfo.customers
			if (!ctrl.forceOwnerEmpty)
				ctrl.setSelectedOwner();

		};

		var failureCallback = function (error) {

			ctrl.isLoadingSecondStep = false

			var title = gettextCatalog.getString("ic-error-modal-title");
			var message = gettextCatalog.getString("ic-get-documenttype-error-modal-message");
			var originalError = angular.copy(error);

			if (utilsFactory.isNullOrUndefined(error.data)) {
				switch (error.status) {
					case errorConstants.ERROR.HTTP_STATUS.UNAUTHORIZED:
						message = gettextCatalog.getString("global-status-unauthorized-error");
						break;
					case errorConstants.ERROR.HTTP_STATUS.INTERNAL_SERVER_ERROR:
						message = gettextCatalog.getString("global-status-internal-error");
						break;
					default:
						message = gettextCatalog.getString("global-status-error");
						break;
				}
				errorFactory.openSendErrorModalDialog(title, message, originalError);

				return;
			} else {
				error = error.data;
			}

			switch (error.errorCode) {
				case errorConstants.ERROR.GENERIC_ERROR:
					message = gettextCatalog.getString("ic-get-documenttype-generic-error");
					break;
				case errorConstants.ERROR.REQUEST_ERROR:
					message = gettextCatalog.getString("ic-get-documenttype-request-error");
					break;
				case errorConstants.ERROR.UNAUTHORIZED:
					message = gettextCatalog.getString("ic-get-documenttype-unauthorized-error");
					break;
				case errorConstants.ERROR.COMPANY_WORKER_ERROR:
					message = gettextCatalog.getString("ic-get-documenttype-company-error");
					break;
				default:
					message = gettextCatalog.getString("ic-get-documenttype-error-modal-message");
					break;
			}
			errorFactory.openSendErrorModalDialog(title, message, originalError);

		};

		archiveComponentFactory.getFormInfo(successCallback, failureCallback, true)
	}

	ctrl.resetSelectedOwner = function () {
		ctrl.selectedOwner = null
		if(ctrl.contribuente){
			ctrl.editedContribuente = ctrl.originalContribuente
			ctrl.onOwnerUdate({ selectedOwner: null, newDocumentOwner: null, validations: {}, contribuente: ctrl.originalContribuente })
		}
		ctrl.showContribuente = false
		ctrl.newDocumentOwner = {
			personalDetails: {
				name: null,
				lastName: null
			},
			businessName: null,
			fiscalCode: null,
			vatCode: null
		}
		ctrl.disableCFAndVat = false
		ctrl.disableNameFields = true

		ctrl.onFormChange()
		validate()
	}

	ctrl.onFormChange = function () {
		ctrl.validations.vatCodeValidation.status = "NO_ERROR";
		ctrl.validations.fiscalCodeValidation.status = "NO_ERROR";
		ctrl.showFormInfo()
		ctrl.onOwnerUdate({ selectedOwner: null, newDocumentOwner: null, validations: {}, contribuente: null })
		if (ctrl.selectedOwner && ctrl.selectedOwner.id)
			ctrl.onOwnerUdate({ selectedOwner: ctrl.selectedOwner, newDocumentOwner: null, validations: {}, contribuente: ctrl.showContribuente ? ctrl.editedContribuente : null })
		else {
			var validationsOwner = {}
			if (ctrl.newDocumentOwner.vatCode) {
				ctrl.newDocumentOwner.vatCode = ctrl.newDocumentOwner.vatCode.toUpperCase()
				ctrl.validations.vatCodeValidation.validate(ctrl.newDocumentOwner.vatCode);
				if (ctrl.validations.vatCodeValidation.status !== "NO_ERROR" || (ctrl.validations.vatCodeValidation.status === 'NO_ERROR' && ctrl.showSearch()))
					validationsOwner.vatCode = "ERROR"
			}
			if (ctrl.newDocumentOwner.fiscalCode) {
				ctrl.newDocumentOwner.fiscalCode = ctrl.newDocumentOwner.fiscalCode.toUpperCase()
				ctrl.validations.fiscalCodeValidation.validate(ctrl.newDocumentOwner.fiscalCode);
				if (ctrl.validations.fiscalCodeValidation.status !== "NO_ERROR" || (ctrl.validations.fiscalCodeValidation.status === 'NO_ERROR' && ctrl.showSearch()))
					validationsOwner.fiscalCode = "ERROR"
			}
			ctrl.onOwnerUdate({ selectedOwner: null, newDocumentOwner: ctrl.newDocumentOwner, validations: validationsOwner, contribuente: ctrl.showContribuente ? ctrl.editedContribuente : null })
		}
	}
	var validate = function () {
		var validated = true;
		if (ctrl.category === 'DOCUMENTI_GENERICI') {
			ctrl.validations.vatCodeValidation.validate(ctrl.newDocumentOwner.vatCode);
			if (ctrl.validations.vatCodeValidation.status !== "NO_ERROR") {
				validated = false;
			}

			ctrl.validations.fiscalCodeValidation.validate(ctrl.newDocumentOwner.fiscalCode);
			if (ctrl.validations.fiscalCodeValidation.status !== "NO_ERROR") {
				validated = false;
			}
		}

		return validated;
	};

	ctrl.selectedOwnerUpdate = function (owner) {
		var successCallback = function (data) {
			modalFactory.dismissWaitModalDialog();
			ctrl.selectedOwner = owner
			ctrl.newDocumentOwner = {
				personalDetails: data.personalDetails || null,
				businessName: data.businessName || null,
				fiscalCode: data.fiscalCode || null,
				vatCode: data.vatCode || null,
				id: data.id || null
			}
			ctrl.disableCFAndVat = true
			ctrl.disableNameFields = true
			validate()
			ctrl.onFormChange()

		}

		var failureCallback = function (error) {

			modalFactory.dismissWaitModalDialog();

			var title = gettextCatalog.getString("clbc-owc-grid-error-modal-title");
			var message = gettextCatalog.getString("clbc-owc-grid-error-modal-message");
			var originalError = angular.copy(error);

			if (utilsFactory.isNullOrUndefined(error.data)) {
				switch (error.status) {
					case errorConstants.ERROR.HTTP_STATUS.BAD_REQUEST:
						message = gettextCatalog.getString("global-status-unauthorized-error");
						break;
					case errorConstants.ERROR.HTTP_STATUS.UNAUTHORIZED:
						message = gettextCatalog.getString("global-status-unauthorized-error");
						break;
					case errorConstants.ERROR.HTTP_STATUS.FORBIDDEN:
						message = gettextCatalog.getString("global-status-forbidden-error");
						break;
					case errorConstants.ERROR.HTTP_STATUS.INTERNAL_SERVER_ERROR:
						message = gettextCatalog.getString("global-status-internal-error");
						break;
					default:
						message = gettextCatalog.getString("global-status-error");
						break;
				}
				errorFactory.openSendErrorModalDialog(title, message, originalError, ctrl.control.reloadList);
				return;
			} else {
				error = error.data;
			}

			switch (error.errorCode) {
				case errorConstants.ERROR.REQUEST_ERROR:
					message = gettextCatalog.getString("clbc-owc-order-request-error");
					break;
				case errorConstants.ERROR.UNAUTHORIZED:
				case errorConstants.ERROR.PERMISSION_ERROR:
					message = gettextCatalog.getString("clbc-owc-order-permission-error");
					break;
				case errorConstants.ERROR.COMPANY_WORKER_ERROR:
					message = gettextCatalog.getString("clbc-owc-order-company-error");
					break;
				case errorConstants.ERROR.GROUPMEMBERSHIP_NOT_FOUND:
					message = gettextCatalog.getString("clbc-owc-order-company-error");
					break;
				default:
					message = gettextCatalog.getString("clbc-owc-grid-error-modal-message");
					break;
			}
			errorFactory.openSendErrorModalDialog(title, message, originalError, ctrl.control.reloadList);

		};

		editAndUploadModalFactory.getOwner(owner.id, successCallback, failureCallback)
	}

	ctrl.showFormInfo = function () {
		return utilsFactory.isBlank(ctrl.newDocumentOwner.vatCode) && utilsFactory.isBlank(ctrl.newDocumentOwner.fiscalCode)
	}

	ctrl.showSearch = function () {
		return ctrl.disableNameFields &&
			!ctrl.disableCFAndVat &&
			((utilsFactory.isNotBlank(ctrl.newDocumentOwner.vatCode) && ctrl.validations.vatCodeValidation.status === 'NO_ERROR') ||
				(utilsFactory.isNotBlank(ctrl.newDocumentOwner.fiscalCode) && ctrl.validations.fiscalCodeValidation.status === 'NO_ERROR'))
	}

	ctrl.disableVatCodeField = function () {
		return (ctrl.selectedOwner && ctrl.selectedOwner.id) ||
			ctrl.disableCFAndVat ||
			(!ctrl.disableCFAndVat && utilsFactory.isNotBlank(ctrl.newDocumentOwner.fiscalCode))
	}

	ctrl.disableFiscalCodeField = function () {
		return (ctrl.selectedOwner && ctrl.selectedOwner.id) ||
			ctrl.disableCFAndVat ||
			(!ctrl.disableCFAndVat && utilsFactory.isNotBlank(ctrl.newDocumentOwner.vatCode))
	}

	ctrl.searchExistingOwner = function () {
		var vatCodeOrCf;
		if(utilsFactory.isNotBlank(ctrl.newDocumentOwner.vatCode)) {
			vatCodeOrCf = ctrl.newDocumentOwner.vatCode
		}
		if(utilsFactory.isNotBlank(ctrl.newDocumentOwner.fiscalCode)) {
			vatCodeOrCf = ctrl.newDocumentOwner.fiscalCode
		}

		modalFactory.openWaitModalDialog();
		var successCallback = function (data) {

			if(utilsFactory.isNotBlank(data.fiscalCode) || utilsFactory.isNotBlank(data.vatCode))
			{
				ctrl.newDocumentOwner = {
					personalDetails: data.personalDetails || {name: null, lastName: null},
					businessName: data.businessName || null,
					fiscalCode: data.fiscalCode || null,
					vatCode: data.vatCode || null,
					id: data.id || null
				}

				ctrl.disableCFAndVat = true
				ctrl.disableNameFields = true
			} else {
				ctrl.fetchOwnerCallback({"type": 'not_found'})
				ctrl.disableCFAndVat = false
				ctrl.disableNameFields = false
			}

			validate()
			ctrl.onFormChange()
			modalFactory.dismissWaitModalDialog();
		}

		var failureCallback = function (error) {
			ctrl.fetchOwnerCallback({"type": 'error'})
			modalFactory.dismissWaitModalDialog();
		}

		titolareFactory.fetchOwner(vatCodeOrCf, successCallback, failureCallback);
	}

	ctrl.changedVatOrCf = function () {
		ctrl.newDocumentOwner.businessName = null
		ctrl.newDocumentOwner.personalDetails.name = null
		ctrl.newDocumentOwner.personalDetails.lastName = null

		ctrl.disableNameFields = true

		if(ctrl.autoSearchTimer) {
			clearTimeout(ctrl.autoSearchTimer)
		}
		if(/^(\d{11})$|^(IT\d{11})$/.test(ctrl.newDocumentOwner.vatCode) && ctrl.validations.vatCodeValidation.status === 'NO_ERROR') {
			ctrl.autoSearchTimer = setTimeout(function (){
				ctrl.autoSearchTimer = null
				ctrl.searchExistingOwner()
			}, 500)
			return
		}
		if(/^(\d{11})$|^(IT\d{11})$/.test(ctrl.newDocumentOwner.fiscalCode) && ctrl.validations.fiscalCodeValidation.status === 'NO_ERROR') {
			ctrl.autoSearchTimer = setTimeout(function (){
				ctrl.autoSearchTimer = null
				console.log('TRIGGERED TIMEOUT FOR CF')
				ctrl.searchExistingOwner()
			}, 500)
		}
	}

	ctrl.searchClicked = function () {
		if(ctrl.showSearch()) {
			ctrl.searchExistingOwner()
		}
	}

	ctrl.hideNameForm = function () {
		return ((ctrl.selectedOwner && ctrl.selectedOwner.id) || ctrl.disableNameFields) &&
			utilsFactory.isBlank(ctrl.newDocumentOwner.businessName) &&
			utilsFactory.isBlank(ctrl.newDocumentOwner.personalDetails.name) &&
			utilsFactory.isBlank(ctrl.newDocumentOwner.personalDetails.lastName)
	}
}
angular.module('sinossi.services').factory('titolareService', [
    '$resource',
    '$http',
    'globalFactory',
    'mainConstants',
    function ($resource, $http, globalFactory, mainConstants) {
        var resources = {};
        if (mainConstants.USE_MOCK) {
            resources.fetchOwner = $resource(globalFactory.baseApiUrl + "owners/fetch/:vatCode");
        } else {
            resources.fetchOwner = $resource(globalFactory.baseApiUrl + "owners/fetch/:vatCode");
        }
        return resources;
    }
])
angular.module('sinossi.components').component('titolareComponent', {
	templateUrl: 'scripts/components/titolareComponent/views/titolareTemplate.html',
	controller: titolareController,
	bindings:{
		selectedOwner: "<?",
		forceOwnerEmpty: "<?",
		customers: "<?",
		category: "<",
		onOwnerUdate: "&",
		contribuente: "<?",
		fetchOwnerCallback: "&"
	}
});
angular.module('sinossi.factories').factory('titolareFactory', [
    'titolareService',
    'globalFactory',
    'errorFactory',
    function (titolareService, globalFactory, errorFactory) {

        var fetchOwner = function (
            vatCodeOrCF,
            successCallback,
            failureCallback
        ) {
            var queryParams = {
                vatCode: vatCodeOrCF
            }

            titolareService.fetchOwner.get(queryParams,
                function(data) {
                    successCallback(data)
                },
                function(error) {
                    errorFactory.dispatchError(error, failureCallback)
                }
            )
        }
        return {
            fetchOwner: fetchOwner
        }
    }]
)