TextControl = require './text'
###
	Initialize with {item:{skin instance},attribute:'attribute',options:{options from meta}}
###
cls                 = 'validate invalid valid'
urlRegex            = /^((https?|ftp):\/\/)?((\w+|\*)\.)?[0-9a-z\-]+(\.([a-z]+|\*))?\.([a-z]+|\*)/i
emailRegex          = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

class URL extends TextControl
	className: 'control control-url'
	type 	 : null
	lastURL  : null
	events:
		'input  input' : 'onInput'
		'keyup  input' : 'onInput'
		'focus  input' : 'onFocus'
		'invalid'      : 'onInvalidURL'
		'valid'        : 'onValidURL'

	elements:
		'input': 'input'

	constructor: ->
		super
		urlRegex = @options.regex if @options.regex
		@input.bind 'blur', @onBlur
		@checkURL @lastURL, silent: true if @lastURL

	onInput: (e) =>
		@onBlur e if e.which is 13

	checkURL: (url, @opts = {}) =>
		if not url?.length and @options.allowEmpty
			@lastURL = url
			@_onValidationComplete true
			return @

		@el.removeClass cls

		@lastURL = url

		return @_onValidationComplete !url.length or @testURLisValid url if !@type
		return @_onValidationComplete false unless @testURLisValid url
		@$addClass('validate')
		@_checkURL(url).then(=> @_onValidationComplete true).fail => @_onValidationComplete false
		@

	_checkURL: (url) =>
		def = Widgetic.Aye.defer()
		def.resolve()
		def.promise

	_onValidationComplete: (isValid) =>
		@$trigger @updateState isValid
		# don't trigger the change if it's the same url
		@onURL isValid if !@silent and (!@item or @item[@attribute] isnt @lastURL)

	updateState: (valid) =>
		@state = if valid then 'valid' else 'invalid'

	onURL: (exists, options={}) ->
		@onValidURL() if !@silent and exists
		@change @lastURL, $.extend @opts, options if exists
		@

	onBlur: (e) =>
		return @$trigger @state if (@lastURL is (currentURL = ($ e.target).val())) and @state
		if !(@options.allow_email and /@/.test currentURL) and currentURL and !(/^(https?|ftp):\/\//i.test currentURL)
			currentURL = "http://#{currentURL}"
		@checkURL currentURL unless @isNew() and !currentURL
		super

	onFocus: -> @$removeClass 'invalid'

	_change: ->

	onInvalidURL: =>
		@$removeClass(cls).$addClass 'invalid'
		@onURL false unless @silent

	onValidURL: =>
		@$removeClass(cls).$addClass 'valid'

	testURLisValid: (url) =>
		return urlRegex.test url unless @options.allow_email
		urlRegex.test(url) or emailRegex.test url

module.exports = URL
