import { BrowserStorage } from "./browser-storage" ; import * as _ from "lodash" ; import { CoreMessages , SyncResultModel } from "@elevate/shared/models" ; import { Constant } from "@elevate/shared/constants" ; export class Background { public init ( ) { this . listenForExternalMessages ( ) ; this . setBrowserActionBehaviour ( ) ; } private reloadBrowserTab ( tabId ) { console . log ( "Now reloading tab id " + tabId ) ; chrome . tabs . reload ( tabId ) ; } param { SyncResult } syncResult private forwardOnExternalSyncFinished ( syncResult ) { if ( syncResult ) { chrome . tabs . query ( { } , ( tabs ) => { _ . forEach ( tabs , ( tab ) => { if ( ! tab . url ) { const message = { message : CoreMessages . ON_EXTERNAL_SYNC_DONE , results : syncResult } ; chrome . tabs . sendMessage ( tab . id , message ) ; } } ) ; } ) ; } } private listenForExternalMessages ( ) { chrome . runtime . onMessageExternal . addListener ( ( request , sender , sendResponse ) => { switch ( request . method ) { case CoreMessages . ON_EXTERNAL_SYNC_DONE : this . forwardOnExternalSyncFinished ( request . params . syncResult ) ; break ; case CoreMessages . ON_RELOAD_BROWSER_TAB : this . reloadBrowserTab ( request . params . sourceTabId ) ; break ; case BrowserStorage . ON_GET_MESSAGE : BrowserStorage . getInstance ( ) . get ( request . params . storage , request . params . key ) . then ( result => sendResponse ( { data : result } ) , error => { console . error ( error ) ; } ) ; break ; case BrowserStorage . ON_SET_MESSAGE : BrowserStorage . getInstance ( ) . set ( request . params . storage , request . params . key , request . params . value ) . then ( ( ) => sendResponse ( { message : request . params . key + " has been set to " + request . params . value } ) , error => { console . error ( error ) ; } ) ; break ; case BrowserStorage . ON_RM_MESSAGE : BrowserStorage . getInstance ( ) . rm ( request . params . storage , request . params . key ) . then ( ( ) => sendResponse ( { message : request . params . key + " has been removed" } ) , error => { console . error ( error ) ; } ) ; break ; case BrowserStorage . ON_CLEAR_MESSAGE : BrowserStorage . getInstance ( ) . clear ( request . params . storage ) . then ( ( ) => sendResponse ( { message : request . params . storage + " has been cleared" } ) , error => { console . error ( error ) ; } ) ; break ; case BrowserStorage . ON_USAGE_MESSAGE : BrowserStorage . getInstance ( ) . usage ( request . params . storage ) . then ( result => sendResponse ( { data : result } ) , error => { console . error ( error ) ; } ) ; break ; default : throw new Error ( "Not existing method" ) ; } return true ; } ) ; } private setBrowserActionBehaviour ( ) { chrome . browserAction . onClicked . addListener ( ( ) => { chrome . tabs . create ( { url : chrome . extension . getURL ( Constant . APP_ROOT_URL ) } ) ; } ) ; } } const background = new Background ( ) ; background . init ( ) ;