import FirefoxProfile from 'firefox-profile'

const SPECIAL_PROPERTIES = ['extensions', 'proxy']

class FirefoxProfileLaunchService {
    /**
     * modify config and launch sauce connect
     */
    onPrepare (config) {
        this.config = config

        /**
         * don't do anything if no profile is specified
         */
        if (!config.firefoxProfile) {
            return
        }

        this.profile = new FirefoxProfile()

        for (let preference in config.firefoxProfile) {
            /**
             * extensions are getting set at the end
             */
            if (SPECIAL_PROPERTIES.includes(preference)) {
                continue
            }

            this.profile.setPreference(preference, config.firefoxProfile[preference])
        }

        if (this.config.firefoxProfile.proxy) {
            this.profile.setProxy(this.config.firefoxProfile.proxy)
        }

        this.profile.updatePreferences()

        if (!Array.isArray(config.firefoxProfile.extensions)) {
            return this.buildExtension()
        }

        return new Promise((resolve) => {
            this.profile.addExtentsions(this.firefoxProfile.extensions, function () {
                return resolve(this.buildExtension)
            })
        })
    }

    buildExtension () {
        return new Promise((resolve) => {
            this.profile.encoded((zippedProfile) => {
                if (Array.isArray(this.config.capabilities)) {
                    return this.config.capabilities.filter((cap) => cap.browserName === 'firefox').forEach((cap) => {
                        cap.firefox_profile = zippedProfile
                    })
                }

                for (let browser in this.config.capabilities) {
                    if (this.config.capabilities[browser].browserName !== 'firefox') {
                        continue
                    }

                    this.config.capabilities[browser]
                }
            })
        })
    }
}

export default FirefoxProfileLaunchService

@@ -210,16 +210,22 @@
  (config
+, caps
 ) %7B%0A    
@@ -248,16 +248,41 @@
 = config
+%0A        this.caps = caps
 %0A%0A      
@@ -1169,19 +1169,20 @@
 xten
-t
 sions(
-this
+config
 .fir
@@ -1209,19 +1209,13 @@
 ns, 
-function ()
+() =%3E
  %7B%0A 
@@ -1263,16 +1263,18 @@
 xtension
+()
 )%0A      
@@ -1460,33 +1460,18 @@
 y(this.c
-onfig.capabilitie
+ap
 s)) %7B%0A  
@@ -1492,38 +1492,16 @@
     
-return this.config.capabilitie
+this.cap
 s.fi
@@ -1639,32 +1639,69 @@
              %7D)%0A
+                    return resolve()%0A
                 
@@ -1745,33 +1745,18 @@
 n this.c
-onfig.capabilitie
+ap
 s) %7B%0A   
@@ -1782,33 +1782,18 @@
  (this.c
-onfig.capabilitie
+ap
 s%5Bbrowse
@@ -1910,25 +1910,10 @@
 is.c
-onfig.capabilitie
+ap
 s%5Bbr
@@ -1936,16 +1936,50 @@
        %7D
+%0A%0A                return resolve()
 %0A       

install extension properly