class window.CouponCtrl extends BaseCtrl
    constructor: (@$rootScope, @$scope, @$state, @$stateParams, @$injector, @Dock, @Constants, @Coupons, @Analytics, @$dialogs, @$translate, @Cookies) ->
        super()

        if not @Dock.hasSiteData() then @getSite()
        @header = 'coupon.title'
        @errorText = ''
        @timing = {}
        @uploadAnotherPhoto = false
        @showTimingDetails = false
        @id = @$stateParams.id
        @$rootScope.hideButtons = true
        if @Dock.hasCoupon()
            @uploadAnotherPhoto = true
            @timing = @timeConverter(@Dock.data.coupon.redemption.timing)
            @id = @$stateParams.id

    onSiteLoad: (data, headers) =>
        super(data, headers)
        @getCoupon()
        #get cookie token
        @CouponToken = @$injector.get("CouponToken")
        @CouponToken.post({coupon: @id}, @onGetCouponToken, @onCouponTokenError)

    getCoupon: =>
        console.log "getting coupon" if DEBUG
        console.log @$stateParams if DEBUG
        if @id?
            @Coupons.get({id: @id}, @onGetCoupon, @onCouponError)
        else
            @onCouponError('no id')

    redemptionMessage: =>
        JSON.parse(@Dock.data.coupon.redemption.timing).message if @Dock.data.coupon?

    redeemableOn: (day) =>
        return false unless @Dock.data.coupon?
        JSON.parse(@Dock.data.coupon.redemption.timing).times[day].join(', ')

    isRedeemable: =>
        @Dock.data.coupon? && @Dock.data.coupon.redemption.redeemable

    isRedeemableNotNow: =>
        @Dock.data.coupon? && !@Dock.data.coupon.redemption.redeemable && (@Dock.data.coupon.redemption.status == "assigned")

    isRedeemed: =>
        @Dock.data.coupon? && (@Dock.data.coupon.redemption.status == "redeemed") && @justRedeemed

    isAlreadyRedeemed: =>
        @Dock.data.coupon? && (@Dock.data.coupon.redemption.status == "redeemed") && !@justRedeemed

    notAlwaysRedeemable: =>
        return false unless @Dock.data.coupon?
        timing = JSON.parse(@Dock.data.coupon.redemption.timing) 
        !timing.always_available

    onGetCoupon: (data) =>
        console.log "got coupon" if DEBUG
        console.log data  if DEBUG
        @Dock.setCoupon(data)
        @timing = @timeConverter(data.redemption.timing)
        numAnyTime = @occurrences(@Dock.data.coupon.redemption.timing, 'Any Time', false)
        if numAnyTime < 7 then @showTimingDetails = true
        @uploadAnotherPhoto = true

    onCouponError: (data) =>
        console.log "getting coupon failed " if DEBUG
        console.log data  if DEBUG
        @header = 'coupon.title_error'
        @errorText = 'coupon.coupon_not_valid'
        @uploadAnotherPhoto = true

    onGetCouponToken: (data) =>
        console.log "got coupon token #{data.token}" if DEBUG
        @Dock.setUserToken('token '+data.token)
        @Cookies.setItem('sr_token', 'token '+data.token, 31536e3, '/')
        # We assume as long as user authorized by coupon
        # He is not api restricted
        @Cookies.setItem('sr_api_restriction', false, 31536e3, '/') 

    onCouponTokenError: (data) =>
        console.log "getting coupon token failed " if DEBUG

    redeem: =>
        console.log 'Redeeming'
        title = @$translate('coupon.dialog_title')
        message = @$translate('coupon.dialog_message')
        dlg = @$dialogs.confirm(title,message)
        dlg.result.then ((btn) =>
            console.log "then btn is #{btn}"
            @redeemConfirm()
        )

    redeemConfirm: =>
        @Coupons.delete({id: @id}, @onRedeem, @onRedeemError)

    onRedeem: (data) =>
        console.log "coupon redeemed" if DEBUG
        @justRedeemed = true
        @Dock.setCoupon(data)

    onRedeemError: (data) =>
        console.log "redeeming coupon failed " if DEBUG
        @header = 'global.general_error_header'
        @errorText = 'global.general_error'

    ## convert the time component into an object
    ## replace day strings with normal dates so that the array can be sorted
    ## this works because the actual date will not get displayed, we only need the names of the day
    timeConverter: (data) =>
        data = data.replace /monday/, "2013-12-23"
        data = data.replace /tuesday/, "2013-12-24"
        data = data.replace /wednesday/, "2013-12-25"
        data = data.replace /thursday/, "2013-12-26"
        data = data.replace /friday/, "2013-12-27"
        data = data.replace /saturday/, "2013-12-28"
        data = data.replace /sunday/, "2013-12-29"
        JSON.parse(data)

    occurrences: (string, subString, allowOverlapping) ->
        string += ""
        subString += ""
        return string.length + 1  if subString.length <= 0
        n = 0
        pos = 0
        step = (if (allowOverlapping) then (1) else (subString.length))
        loop
            pos = string.indexOf(subString, pos)
            if pos >= 0
                n++
                pos += step
            else
                break
        n


CouponCtrl.$inject = ["$rootScope", "$scope", "$state", "$stateParams", "$injector", "Dock", "Constants", "Coupons", "Analytics", "$dialogs", "$translate", "Cookies"]

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