class window.UploadCtrl extends BaseCtrl
    constructor: (@$scope, @$state, @Dock, @$upload, @Constants, @MixPanel, @$injector) ->
        super()

        console.log "@boardId is #{@boardId}" if DEBUG

        if not @Dock.hasBoard() or not @Dock.hasUserName()
            #check if we have a board id from the url
            if @boardId
                #retrieve info for this board
                @$state.go(@Constants.routes.boardbase, {boardId: @boardId})
            else
                #redirect to home, no board info found
                @$state.go(@Constants.routes.home)

        @imageLoading = false;

    continue: =>
        console.log "file selected " if DEBUG
        #check if image has been uploaded already, don't want to do it twice if it's already there
        if not @Dock.imageUploaded() or not @Dock.imageSubmitted()
            console.log('submitting image') if DEBUG
            console.log '----------- Dock.photo.src = ', @Dock.photo.src
            blob = dataURItoBlob(@Dock.photo.src)
            formData = @Dock.getAWSParams(blob.type)
            host = @Dock.getStorageReadPrefix()
            @Dock.data.imageSubmitted = true;
            if typeof(blob) == 'string'
                host = '@@proxy_url'
                formData.token = '@@proxy_key'
                parts = blob.split(',')
                formData.b64 = parts[1]
                formData.mimeType = parts[0].split(';')[0].split(':')[1]
                formData.uploadPrefix = @Dock.getStorageReadPrefix()
                $http = @$injector.get('$http')
                $http
                    url: host
                    data: formData
                    method: 'POST'
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                .success (data) =>
                    console.log 'Success proxy upload', data
                    @Dock.data.url = data.url
                .error (error) =>
                    console.log 'Error proxy upload' + JSON.stringify(error)

            else
                blob.name = @Dock.photo.name
                @Dock.upload = @$upload.upload
                    url: host
                    data: formData
                    file: blob
                    progress: (evt) =>
                        console.log "Percent: " + parseInt(100.0 * evt.loaded / evt.total)  if DEBUG
                        @Dock.imageUploadingProgress = parseInt(100.0 * evt.loaded / evt.total)
                .success (data) =>
                    console.log "upload successful " if DEBUG
                    @imageUploadSuccess()

                .error (error) =>
                    console.log 'Error uploading image' + error
                    @imageUploadError()

        @$state.go(@Constants.routes.photo, {boardId: @boardId});

    imageUploadSuccess: ->
        console.log "upload success" if DEBUG
        @Dock.setPhotoUrl()
        @Dock.data.imageUploaded = true;
        @Dock.data.imageUploadError = false;
        @MixPanel.trackPhotoUpload()

    imageUploadError: ->
        console.log "upload failed" if DEBUG
        @Dock.data.imageSubmitted = false;
        @Dock.data.imageUploaded = false;
        @Dock.data.imageUploadError = true;

    dataURItoBlob = (dataURI) ->
        console.log "converting to blob " if DEBUG
        byteString = atob(dataURI.split(",")[1])
        mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

        ab = new ArrayBuffer(byteString.length)
        ia = new Uint8Array(ab)
        i = 0
        while i < byteString.length
            ia[i] = byteString.charCodeAt(i)
            i++
        console.log "creating new blob " if DEBUG
        try
            console.debug "trying case 1" if DEBUG
            new Blob([ab], type: mimeString)
        catch e
            window.BlobBuilder = window.BlobBuilder or window.WebKitBlobBuilder or window.MozBlobBuilder or window.MSBlobBuilder
            if e.name is "TypeError" and window.BlobBuilder
                console.debug "case 2" if DEBUG
                return dataURI
            else if e.name is "InvalidStateError"
                # InvalidStateError (tested on FF13 WinXP)
                console.debug "case 3" if DEBUG
                new Blob([ab], type: mimeString)
            else
                # out of luck, blob constructor unsupported entirely
                console.debug "Error - Blob constructor is not supported" if DEBUG


UploadCtrl.$inject = ["$scope", "$state", "Dock", "$upload", "Constants", "MixPanel", "$injector"]

angular.module("shuttlerockApp").controller("UploadCtrl", UploadCtrl)
